Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum function work with recursion and multiple arguments

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.

like image 471
João Calvin Avatar asked Aug 12 '26 05:08

João Calvin


1 Answers

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));
like image 104
Nina Scholz Avatar answered Aug 14 '26 18:08

Nina Scholz