Create function to add such that add(1,2)(3,…k)(1,

2020-04-17 06:41发布

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 !

1条回答
唯我独甜
2楼-- · 2020-04-17 07:10

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

查看更多
登录 后发表回答