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.
f.valueOf, so if you do something likeconsole.log(0 + sum(1)(2)(3))it'll return6; if it's in a string context, it'll usef.toString(e.g.'0' + sum(1)(2)(3)will return'06'); however if there's no particular context, it'll default to a function. You can get rid of the empty parentheses if you do something like+sum(1)(2)(3), but that's probably bad style, since it might create some difficult to debug situationsvalueOfis the best you'll get.