I need a js sum function to work like this:
sum(1)(2) = 3 sum(1)(2)(3) = 6 sum(1)(2)(3)(4) = 10 etc.
I heard it can't be done. But heard that if adding +
in front of sum
can be done. Like +sum(1)(2)(3)(4)
.
Any ideas of how to do this?
Not sure if I understood what you want, but
function sum(n) { var v = function(x) { return sum(n + x); }; v.valueOf = v.toString = function() { return n; }; return v; } console.log(+sum(1)(2)(3)(4));
JsFiddle
This is an example of using empty brackets in the last call as a close key (from my last interview):
sum(1)(4)(66)(35)(0)()
function sum(numberOne) { var count = numberOne; return function by(numberTwo) { if (numberTwo === undefined) { return count; } else { count += numberTwo; return by; } } } console.log(sum(1)(4)(66)(35)(0)());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With