hktir hktir - 1 month ago 10
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

You could use another variable as closure for the factor.

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

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

console.log(addProgressively(3)(4)(5));

Comments