Allow One Function Call

javascript, functions, leetcode2666

Main project image

In this example, a function fn is passed in as an argument in the once function. The first time the returned function is invoked, it should return the same result as fn. Any subsequent invocations should return undefined.

Consider the following. A variable calledOnce is set. When the once function is invoked, a closure is formed with fn and calledOnce due to the inner function referencing the outer scope.

The inner function accepts a rest parameter - which allows a function to accept an indefinite number of arguments as an array. It checks if calledOnce has been set to true to see if it has been invoked earlier. Otherwise, the rest of the code block is executed.

var once = function(fn) {
    let calledOnce = false;

    return function(...args){
        if (!calledOnce) {
            let value = fn(...args)
            calledOnce = true;
            return value
        }
    }
};

/**
 * let fn = (a,b,c) => (a + b + c)
 * let onceFn = once(fn)
 *
 * onceFn(1,2,3); // 6
 * onceFn(2,3,6); // returns undefined without calling fn
 */