Create function to add such that add(1,2)(3,…k)(1,2,3)…(n) should sum all numbers [duplicate]

I have been looking for a way to create an 'add' function such that :

add(1,2) //returns 1+2= 3
add(1)(2,3)(4) // returns 10
add(1)(2,3)(4)(5,6)(7,8,9) //returns 45

I am able to create add method if I know the number of arguments we have, for e.g.:

const add5 = a => b => c => d => e => a+b+c+d+e;

So, if I used add5(1)(2)(3)(4)(5), this will give me the expected output.

But the problem is how to tackle the problem if we have to return sum of 'N' parameters.

TIA !

Answers:

Answer

It's not possible in the general case unless toString coercion is allowed on the result of calling add (or unless the number of calls is known in advance):

function add(...next) {
  let count = 0;
  // return a callable function which, when coerced to a string,
  // returns the closure's `count`:
  function internalAdd(...next) {
    count += next.reduce((a, b) => a + b, 0);
    return internalAdd;
  }
  internalAdd.toString = () => count;
  return internalAdd(...next);
}

console.log('' + add(1,2)) //returns 1+2= 3
console.log('' + add(1)(2,3)(4)) // returns 10
console.log('' + add(1)(2,3)(4)(5,6)(7,8,9)) //returns 45

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.