8 回答
TA贡献1854条经验 获得超8个赞
最简单最完美实现
// es6
const mul = (x) => {
let sum = x
let curried = (y) => {
sum = sum * y
return curried
}
curried.toString = () => sum
return curried
}
console.log(mul(1)) //1
console.log(mul(1)(2))//2
console.log(mul(1)(2)(3))//6
console.log(mul(1)(2)(3)(4))//24
...
// es5
function mul(x){
var sum = x
var curried = function(y){
sum = sum * y
return curried
}
curried.toString=function(){
return sum
}
return curried
}
console.log(mul(1)) //1
console.log(mul(1)(2))//2
console.log(mul(1)(2)(3))//6
console.log(mul(1)(2)(3)(4))//24
...
TA贡献1874条经验 获得超12个赞
var f = (function() {
let r = 1;
return function f(...args){
r *= args.reduce((p, n) => p * n);
f.valueOf = () => r;
return f;
}
}());
f(3)(4)(4)
TA贡献1827条经验 获得超8个赞
var a = function(x) {
return function(y) {
return function(z) {
console.log(x * y * z);
return x * y * z;
};
};
};
TA贡献1829条经验 获得超7个赞
Function Currying
Simple, Beautiful, Interesting
function curry(fn, ...args){
return args.length === fn.length ?
fn(...args) :
(...next_args) => curry(fn, ...args, ...next_args);
}
Next
function mul(a, b, c){
return a * b * c;
}
// mul(3, 4, 4); => 48
let a = curry(mul);
a(3)(4)(4);
// => 48
a(3, 4, 4);
// => 48
a(3)(4, 4);
// => 48
a()()()()()(3, 4)(4);
// => 48
S
TA贡献1775条经验 获得超8个赞
let total;
function a(m){
total = m;
return function(n){
return a(m*n)
}
}
a(3)(4)(4)
console.log(total) //48
添加回答
举报