编写一个函数来打印以这种方式接受参数的总和: sum(2)(3) 并输出 5
What you're looking for is functional currying.
ES6
let sum = (first) => (second) => first + second;
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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.