-3

How do I implement a adder function in javascript which can be invoked like

adder(1,2)(5,6,2)(4,9,10,11)(6,7).....()

The function should accept any number of arguments and add them all together. The function can be invoked in following ways.

adder(2,3,5) // prints 10
adder(2,3)(5) // prints 10
adder(2)(3)(5) //prints 10

What is best possible way to implement this function using closures?

SatishP
  • 23
  • 3
  • Why do you want to implement this syntax? – Trott Jun 06 '17 at 18:44
  • Read about currying - http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html, https://stackoverflow.com/questions/5176313/javascript-curry – Seth Flowers Jun 06 '17 at 18:44
  • you could use the [`arguments`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments) object for variable parameters of the function. – Nina Scholz Jun 06 '17 at 18:50
  • sorry, this was marked as a duplicate... there is simple solution to this; the linked answer performs convoluted and unnecessary steps. This question got closed before I could post my answer, but the gist was: use the `arguments` object to loop thru each passed number, summing those to a value like `sum`. At the end of the function, return `adder.bind( null, sum )`. Calling this returned function will add each number you pass it with the previous sum. – sethro Jun 06 '17 at 19:03

1 Answers1

0
function add(...values){
 this.value=(this.value||0)+values.reduce((a,b)=>a+b),0);
 return add.bind(this);
}

You need a way to pass the value out of your function, i put the value into the context:

add(1,2,3)(4,5);
alert(value);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151