0

I have a problem with suming up an infinite number of arguments in brackets for function sum(). I make a function that can sum two brackets with arguments for sum function, but I do not understand how can I sum a various count of brackets...

I would be grateful for the answer.

function sum(a) {

  return function(b) {
    return a + b; //     
  };
}

console.log(sum(1)(2)); // 1 + 2
console.log(sum(1)(2)(3)); // 1 + 2 + 3
console.log(sum(5)(-1)(2));
console.log(sum(6)(-1)(-2)(-3));
console.log(sum(0)(1)(2)(3)(4)(5));
HarshitMadhav
  • 4,769
  • 6
  • 36
  • 45
Sviat Kuzhelev
  • 1,758
  • 10
  • 28
  • You may want to take a look at [this](https://www.sitepoint.com/currying-in-functional-javascript/) for some ideas. – Federico klez Culloca Dec 19 '17 at 15:57
  • I guess curry works, if final length of arguments are known. – Vipin Kumar Dec 19 '17 at 15:58
  • This seems like an online question or homework, while they are on topic I'm not a fan of providing code for them, I feel it ruins the point of them, **however** I don't mind pointing you in the right direction, always return a function and have a look at [valueOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf) which can work on functions. – George Dec 19 '17 at 15:59
  • `return sum(a + b)` to return another function. You can provide an `arguments.length` check to return `a` when no arg is provided. `sum(2)(3)(4)(5)(); // 14` –  Dec 19 '17 at 15:59
  • I suggest reading [this](http://2ality.com/2011/09/currying-vs-part-eval.html). – pishpish Dec 19 '17 at 16:03

0 Answers0