I am stuck with this problem: I want to write a function in javascript named sum
that sums the subsequent arguments like this:
sum(1)(2)= 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10,
and so on. I wrote this code
function sum(a) {
let currentSum = a;
function f() {
if (arguments.length == 1) {
currentSum += arguments[arguments.length - 1];
return f;
} else {
return currentSum;
}
}
f.valueOf = () => currentSum;
f.toString = () => currentSum;
return f;
}
This code works fine if I put empty parentheses at the end of the call like this: sum(1)(2)(3)() = 6
. Is there any way to modify the code so that I can get rid of the empty parentheses?
I appreciate any help. Thanks in advance.