Search code examples
javascriptfunctional-programmingfunctor

Is it possible to make a functor in JavaScript?


I'm trying to make a function that holds state but is called with foo().
Is it possible?


Solution

  • I believe this is what you want:

    var foo = (function () {
        var state = 0;
    
        return function () {
            return state++;
        };
    })();
    

    Or, following the Wikipedia example:

    var makeAccumulator = function (n) {
        return function (x) {
            n += x;
            return n;
        };
    };
    
    var acc = makeAccumulator(2);
    
    alert(acc(2)); // 4
    alert(acc(3)); // 7
    

    JavaScript is one of those languages that has, IMHO, excellent support for functions as first class citizens.