STE*_*EEL 5 javascript arrays functional-programming currying
请在将其标记为重复之前阅读.
我不是要求单一的咖喱电话.
这个函数乘以乘法(4,4,4)// 64
function multiplication(...args) {
return args.reduce((accum, val) => accum * val, 1)
}
Run Code Online (Sandbox Code Playgroud)
但我试图实现别的......
同样的功能也应该乘以其咖喱函数括号.例如
/*
which return the multiplication of three numbers.
The function can be called in any of the following forms:
multiply(2, 3)(4) => 24
multiply(2)(3, 4) => 24
multiply(2)(3)(4) => 24
multiply(2, 3, 4) => 24
*/
Run Code Online (Sandbox Code Playgroud)
请帮助.
在摆弄了大量代码并阅读一些堆栈答案之后.最后我想出来了.但它仍然不能满足这一要求multiply(2)(3, 4) => 24
但对于其他情况,它可以正常工作
multiply(2,3,4)
multiply(2,3)(4)
multiply(2)(3)(4)
var multiply = function(...args) {
if (args.length === 3) {
return args[0] * args[1] * args[2];
} else {
return function() {
args.push([].slice.call(arguments).pop());
return multiply.apply(this, args);
};
}
}
Run Code Online (Sandbox Code Playgroud)
而 multiply(2)(3, 4) => 24 fail
4ca*_*tle 11
这是一个通用的解决方案,通过重复调用bind直到有足够的参数传递为止.
function curry(func, arity = func.length) {
return function (...args) {
if (args.length >= arity) {
return func(...args);
} else {
return curry(func.bind(this, ...args), arity - args.length);
}
};
}
const multiply = curry((a, b, c) => a * b * c);
console.log(multiply(2, 3)(4));
console.log(multiply(2)(3, 4));
console.log(multiply(2)(3)(4));
console.log(multiply(2, 3, 4));Run Code Online (Sandbox Code Playgroud)
你的代码
var multiply = function(...args) {
if (args.length === 3) {
return args[0] * args[1] * args[2];
} else {
return function() { // ***
args.push([].slice.call(arguments).pop()); // ***
return multiply.apply(this, args);
};
}
}
Run Code Online (Sandbox Code Playgroud)
*** 这两行需要改变,你就快到了,事实上非常接近
var multiply = function(...args) {
if (args.length === 3) {
return args[0] * args[1] * args[2];
} else {
return function() { // ***
args.push([].slice.call(arguments).pop()); // ***
return multiply.apply(this, args);
};
}
}
Run Code Online (Sandbox Code Playgroud)
ES6 让它变得更加干净
var multiply = function(...args) {
if (args.length === 3) {
return args[0] * args[1] * args[2];
} else {
return function(...args2) { // ***
args.push(...args2); // ***
return multiply.apply(this, args);
};
}
}
console.log(multiply(2, 3)(4))
console.log(multiply(2)(3, 4))
console.log(multiply(2)(3)(4))
console.log(multiply(2, 3, 4))Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1421 次 |
| 最近记录: |