Someone ask me an question to write an closure function which should return the sum of input provided and input can be one argument upto n.
so user can call
sum(5) OR sum(4)(3) OR sum(1)(2)...(n),
I wrote the below function using recursion but facing an issue where I need to add an empty parentheses at the end for the below function to work,
function sum(x) {
return function (y) {
if (y) {
return sum(x + y);
}
else {
return x;
}
}
}
// this result in 12 as I am using an empty parentheses at the end
console.log(sum(5)(6)(1)());
// below two will return output as [Function]
console.log(sum(5)(6)(1)(5)(6)(1));
console.log(sum(5));
is there any better way to implement this?