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

问题: This question already has an answer here: “add” function that works with different combinations of chaining/arguments 4 answers I have been looking...

问题:

This question already has an answer here:

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:

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

  • 发表于 2019-01-21 05:08
  • 阅读 ( 174 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除