创建添加的函数,添加(1,2)(3,... k)(1,2,3)......(n)应该对所有数字求和

Vai*_*uri 2 javascript ecmascript-6

我一直在寻找一种创建'添加'功能的方法,以便:

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
Run Code Online (Sandbox Code Playgroud)

如果我知道我们拥有的参数数量,我可以创建add方法,例如:

const add5 = a => b => c => d => e => a+b+c+d+e;
Run Code Online (Sandbox Code Playgroud)

所以,如果我使用add5(1)(2)(3)(4)(5),这将给我预期的输出.

但问题是如果我们必须返回'N'参数的总和,如何解决问题.

TIA!

Cer*_*nce 5

除非toString在调用结果上允许强制add(或者除非提前知道呼叫数量),否则在一般情况下是不可能的:

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
Run Code Online (Sandbox Code Playgroud)