0

How can I realize the below?

console.log(Sum(1))          // 1
console.log(Sum(1)(2))       // 3
console.log(Sum(1)(2)(3))    // 6
console.log(Sum(1)(2)(3)(4)) // 10

I've tried,

var add = function(x) {
    return function(y) { return x + y; };
}

But that's only good for one dive.

j08691
  • 204,283
  • 31
  • 260
  • 272
Mike K
  • 7,621
  • 14
  • 60
  • 120
  • 1
    How exactly do you imagine `Sum(1)` to be `1`, but then `Sum(1)(2)` which is `1(2)` to make any sense? – ASDFGerte Nov 25 '19 at 16:10
  • I don't find any reason for which this question is downvoted... – Maheer Ali Nov 25 '19 at 16:15
  • @MaheerAli He is asking for something which is logically impossible, and not in any difficult-to-see way. Similar questions have also been asked over and over (see the dupe, but also e.g. [this question](https://stackoverflow.com/questions/50279242/currying-function-with-unknown-arguments-in-javascript)). I come to the conclusion he simply didn't think/research about the issue for more than a few minutes, which is enough for me to downvote. Maybe he did, and just had a bad day (that happens to everyone sometimes!), but "eating a downvote" for one of these rare events is not too big a problem. – ASDFGerte Nov 25 '19 at 16:21

1 Answers1

1

Basically you need to return a function with a toString method for getting a value, if not called as function.

function sum(x) {
    function _(y) { x += y; return _; };
    _.toString = function () { return x; };
    return _;
}

console.log(sum(1))          // 1
console.log(sum(1)(2))       // 3
console.log(sum(1)(2)(3))    // 6
console.log(sum(1)(2)(3)(4)) // 10
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392