Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 821
the_drow Avatar asked Jul 14 '09 10:07

the_drow


1 Answers

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.

like image 92
Ionuț G. Stan Avatar answered Oct 26 '22 04:10

Ionuț G. Stan