创建要添加的函数,使得add(1,2)(3,... k)(1,2,3)...(n)应该对所有数字求和 [英] Create function to add such that add(1,2)(3,...k)(1,2,3)...(n) should sum all numbers

查看:135
本文介绍了创建要添加的函数,使得add(1,2)(3,... k)(1,2,3)...(n)应该对所有数字求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种创建添加"功能的方法,例如:

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

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

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;

因此,如果我使用add5(1)(2)(3)(4)(5),这将为我提供预期的输出.

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

但是问题是如果必须返回"N"个参数的总和,该如何解决这个问题.

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

TIA!

推荐答案

在一般情况下,除非在调用add的结果上允许toString强制转换(或者除非事先知道调用次数),否则通常是不可能的):

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

这篇关于创建要添加的函数,使得add(1,2)(3,... k)(1,2,3)...(n)应该对所有数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆