stack_pooper
stack_pooper

Reputation: 287

How can I get this javascript function to call itself?

As of right now my sum function looks like the code below. It works and returns the sum of the consecutive calls. But how can I make this work without the empty parenthesis at the end? Like so theSum(5)(4)(3) which returns 12.

function theSum(x) {
    var total = x;

    function rec(y) {
        if (y === undefined) return total;
        total += y;
        return rec;
    };

    return rec;
}

console.log(theSum(5)(4)(3)()); // 12

Upvotes: 2

Views: 81

Answers (3)

Sylwester
Sylwester

Reputation: 48745

Closures and JavaScript duck typing to the rescue:

function NumSumFun(initial){
    function NumSumNext(num) {
          initial+= num;
      return NumSumNext;
    }
    NumSumNext.valueOf = function () { return initial; }
    return NumSumNext;
}

var x = NumSumFun(10)(29); // ==> function 39
x + 1; // ==> 40

So whats happening. It returns a function but the function has a valueOf property that has access to the accumulated value so the function acts as a number when used as a number.

Upvotes: 0

php_nub_qq
php_nub_qq

Reputation: 16045

Here is a suggestion utilizing a toString method:

function theSum(x) {
    var total = x;

    function rec(y) {
        total += y;
        return rec;
    };

    rec.toString = function() { return total; }

    return rec;
}

alert(theSum(5)(4)(3));

console.log(parseInt(theSum(5)(4)(3)));

Note however that you need to convert the returned reference to a string in some way so that you see the result.

Upvotes: 1

user6101582
user6101582

Reputation:

This is not possible. A function cannot return a function and an integer. You can make theSum(5, 4, 3) = 12 or theSum([5, 4, 3]) = 12.

Upvotes: 0

Related Questions