2

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
2
  • 2
    You could use a toString method. I can't imagine where this kind of chaining will be useful :? Commented Mar 28, 2016 at 22:49
  • 1
    Its not really clear what youre trying to achieve, besides the obvious. But why the chain, I dont get it. My original answer, solved this issue, in a different way, but you didnt find it useful. So be more concise as to why you want to do it this way. as @php_nub_qq says. "I cant imagine where this could be useful" So let us know, wh its useful to you. And why is theSum(5)(4)(3) more important to achieve to you, than theSum(5)(4)(3)() or theSum([5,4,3])? Or is this a homework question, and you're not even sure youirself Commented Mar 28, 2016 at 23:04

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This returns { [Function: rec] toString: [Function] } in NodeJS
@stack_pooper yes, that is what it returns, converting it to a string is where the magic happens. Nice name btw.
0

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.