hktir hktir - 2 years ago 84
Javascript Question

Keeping state in curried function

Is there a way to keep some sort of internal state while writing a curried function?

For example, let's say I want to write a curried function that takes into account the number of times the function was called previously.

I.e. addProgressively(3)(4)(5) = 1*3 + 2*4 + 3*5 = 26.

My approach is to add some counter that increments every time a new curried function is returned but I can't find a good way to keep track of that argument within the addProgressively function.

Answer Source

You could use another variable as closure for the factor.

function addProgressively(x) {
    var factor = 1,
        sum = factor * x;

    function f(y) {
        sum += factor * y;
        return f;
    f.toString = function () { return sum; };
    return f;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download