简体   繁体   English

编写一个函数,其中“ sum(2,3)”和“ sum(2)(3)”的输出均为5

[英]Write a function where the output for both “sum(2,3)” and “sum(2)(3)” will be 5

Recently I come up with a question in an interview which is "write a function which will output of these two will same sum(2,3) and sum(2)(3), that is 5". 最近,我在一次采访中提出一个问题:“编写一个函数,这两个函数的输出将相同sum(2,3)和sum(2)(3),即5”。

Please give any idea if it is possible. 如果可以的话,请给我任何想法。

Thanks in advance 提前致谢

For sum(x)(y) , have sum(x) return another function, f, such that f(y) - ie. 对于sum(x)(y) ,让sum(x)返回另一个函数f,这样f(y) -即。 (sum(x))(y) - evaluates to the correct result. (sum(x))(y) -计算得出正确的结果。 See Eloquent JavaScript: Higher-Order Functions for examples on how closures - and returning functions from functions - make this possible. 有关闭包(以及从函数返回函数)如何实现此功能的示例,请参见Eloquent JavaScript:高阶函数

The arguments.length property can be used to determine how many arguments have been supplied to the ( sum ) function and react accordingly: either the immediate sum, for sum(x, y) , or the aforementioned 'curried' function when invoked with a singular argument. arguments.length属性可用于确定已向( sum )函数提供了多少个参数并做出相应的反应: sum(x, y)的立即和,或使用a调用时提到的“ curried”函数单个参数。

(The linked "Curried JavaScript functions: no, not curried spicy, but curried lambda-calculus-like" article actually contains a solution in full.. but it feels that to provide the code here would be cheating.) (链接的“咖喱JavaScript函数:不,不是咖喱辣的,而是咖喱lambda演算类的”文章实际上包含完整的解决方案。但是,感觉在此处提供代码会很容易出错。)

Here's your simple function without counting the args: 这是您不计入args的简单函数:

function sum(a,b){
    if(b===undefined){
        return function(c){ return parseInt(a)+parseInt(c);}
    }
    return parseInt(a)+parseInt(b);
}
console.log(sum(2,3));
console.log(sum(2)(3));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM