As part of the programming task, we are tasked with creating a function with an indefinite number of consecutive calls. As an example, suppose a function returns just the sum of the arguments provided, 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 using the allowed empty function call at the end as an indication of the end of the calls.
I 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 traversal of the function object, which is not ideal. My question here is whether there is a way to solve the problem in a purely recursive way.
As a remark, I do not believe that the problem can be solved if this last empty call () is not specified, but if I am wrong, let me know.
Update
This question was answered in CodeReview: https://codereview.stackexchange.com/a/153999/129579
A neet solution that does not rely on a global scope and is purely functional.
source share