Is there a away to create a sum function that works with both recursive call (e.g (1)(2)(3)(4)), and multiple arguments (e.g (1, 2, 3, 4))?
Like this:
sum(5, 5) // 10
sum(5)(5) // 10
Thank you.
You could return a function for next arguments and implement a toString method.
function sum() {
var add = function (a, b) { return a + b; },
value = Array.prototype.reduce.call(arguments, add, 0);
function f() {
value = Array.prototype.reduce.call(arguments, add, value);
return f;
};
f.toString = function () { return value; };
return f;
}
console.log(sum(5, 5));
console.log(sum(5)(5));
console.log(sum(3, 4, 5)(6, 7));
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