Create a function with an undetermined number of successive calls As part of a programming challenge, we are tasked with creating a function with an undetermined number of successive calls. As an example, let's say the function returns simply the sum of the provided arguments, it should work as follows :

sum(4)() // 4
sum(4)(5)() // 9
sum(4)(5)(9)() // 18
sum(4)(5)(9)(1)() // 19
// etc...


The problem is simplified by the allowed empty function call at the end as an indication of end of calls.

I have worked on a solution that does the job but using global variables inside the function itself :

var sum = function (a) {
    if (!sum.init) {
        sum.total = 0;
        sum.init = true;
    }
    if (!arguments.length) {
        sum.init = false;
        return sum.total;
    }
    sum.total += a;
    return sum;
};


This solution works but uses state, global variables and function object trickery which is not ideal. My question here is whether there is a way to solve the problem in a purely recursive way.

As a side note, I do not believe the problem can be solved if that last empty call () is not provided, but if I'm wrong please let me know.
This solution uses a functional approach with currying, which i find more elegant since it doesn't have to rely on global variables



function sum(total) {
    return function () {
        if (arguments.length == 0) {
         return total;
        } else {
         return sum(total + arguments[0]);
        }
    }
}

console.log(sum(4)()) // 4
console.log(sum(4)(5)()) // 9
console.log(sum(4)(5)(9)()) // 18
console.log(sum(4)(5)(9)(1)()) // 19




The first call to ´sum´, returns the inner function. depending on the number of arguments passed to the inner function, it returns the value of sum's argument as it is or it calls again ´sum´ with the updated running total (thus returning again the inner function to be called again).

The limitation (of this implementation) is that you HAVE TO make a final call with no arguments to have to final value.

See this answer (Method 3: Infinite Level Currying) for an example of using .valueOf to get the result out at every call, even those with arguments.