用JavaScript来处理带有未知参数的函数 [英] Currying function with unknown arguments in JavaScript

查看:120
本文介绍了用JavaScript来处理带有未知参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的一次采访中,我被要求编写一个函数,该函数可以将数字相加并接受如下参数:

In a recent interview, I was asked to write a function that adds numbers and accepts parameters like this:

add(1)(2)(3) // result is 6
add(1,2)(3,4)(5) // result is 15

参数的数量不是固定的,参数可以成组或单独传递.

The number of parameters is not fixed, and the arguments can be either passed in sets or individually.

如何实现此add函数?

推荐答案

给出示例,参数的数量在某些方面是固定的.

Given your examples, the number of parameters is fixed in some ways.

正如@ASDFGerte所指出的那样,您的示例似乎在三次调用后返回了结果.在这种情况下,无需引入可变参数和currying等术语的简单实现就是

As @ASDFGerte pointed out, your examples seem to return the result after three invocations. In this case a simple implementation without introducing terms like variadic and currying could be

function add(...args1){
  return function(...args2){
    return function(...args3){
      return args1.concat(args2).concat(args3).reduce((a,b)=>a+b)}}}
                
console.log(add(1)(2)(3))
console.log(add(1,2)(3,4)(5))

每次调用都接受可变数量的参数.

Every invocation accepts a variable number of parameters.

但是,最好泛化此嵌套函数结构的构造,并且您可以使用currying来实现.

However it would be nice to generalize the construction of this nested functions structure and you can accomplish that with currying.

但是,如果要允许任意数量的调用,何时应该停止返回新函数并返回结果?没有办法知道,这是一个简单,不准确和局部的解释,可让您了解为什么他们说您无法完成他们问您的事情.

But if you want to allow an arbitrary number of invocations, when you should stop returning a new function and return the result? There is no way to know, and this is a simple, unaccurate and partial explanation to give you the idea of why they said you cannot accomplish what they asked you.

因此,最终的问题是:您是否可能误解了这个问题?或者,也许这只是测试您的把戏

So the ultimate question is: is it possible that you misunderstood the question? Or maybe it was just a trick to test you

修改

另一种选择是在没有传入任何参数的情况下实际调用该函数,将调用更改为add(1)(2)(3)()

Another option would be to actually invoke the function when no arguments are passed in, change the call to add(1)(2)(3)()

这是递归实现的示例

function sum (...args) {
  let s = args.reduce((a,b)=>a+b)

   return function (...x) {
     return x.length == 0 ? s : sum(s, ...x)
    };
}
console.log(sum(1,2)(2,3,4)(2)())

每次调用时都会计算当前参数的总和,然后返回一个新函数:

At every invocation computes the sum of current parameters and then return a new function that:

  • 如果不带参数调用仅返回当前总和
  • 如果传入其他数字,则递归调用sum并传递实际的和和新数字

这篇关于用JavaScript来处理带有未知参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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