Search code examples
javascriptfunctionreturninvoke

How would I invoke a function only once, with any further invocations returning the last value from the first invocation?


My goal with the code below is to have whatever function passed into fn to ONLY be invoked once. e.g. result returns 5 and the repeated invocation below should also return that same number. What I have right now keeps returning a new number instead of the same one.

function once(fn) {
    var done = false;
    
    return function () {
        if (!done) {
            done = true;
            return fn.apply(this, arguments);
        } else if (done) {
            return fn.apply(this, arguments);
        }
    };
    
}

function add(x, y) {
    return x + y;
}

var addOnce = once(add);
var result = addOnce(2, 3);
result = addOnce(4, 4);


Solution

  • For getting the same value, you could store the value and return it for every call.

    function once(fn) {
        var done = false,
            value;
    
        return function() {
            if (!done) {
                done = true;
                value = fn.apply(this, arguments);
            }
            return value;
        };
    }
    
    function add(x, y) {
        return x + y;
    }
    
    var addOnce = once(add);
    
    console.log(addOnce(2, 3)); // 5
    console.log(addOnce(4, 4)); // 5