[英]Write a function to print the sum which takes the parameter in this wa: sum(2)(3) and outputs 5
编写一个函数来打印以这种方式接受参数的总和: sum(2)(3) 并输出 5
What you're looking for is functional currying.您正在寻找的是功能性柯里化。
ES6 ES6
let sum = (first) => (second) => first + second;
ES5 ES5
function sum(first){ return function(second){ return first + second;}}
sum(2)(3); //returns 5
Normally, you can achieve just like this通常,您可以像这样实现
function sum(x) {
return y => {
return x + y;
}
}
But it's kind of lack of extensibility.但它缺乏可扩展性。 If you want to calculate
sum(2)(3)(5)
, this function just doesn't work.如果你想计算
sum(2)(3)(5)
,这个函数就不起作用了。
You have to change it to你必须把它改成
function sum(x) {
return y => {
return z => {
return x + y + z;
}
}
}
Here is a common solution, combining recursion and a little trick.这是一个常见的解决方案,结合递归和一个小技巧。
function sum(x) {
var result = x;
function adder(y) {
result += y;
return adder;
}
adder.toString = function() {
return result;
};
return adder;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.