js实现a(3)(4)(4) // print 48
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)
// 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
...
var a = function(x) {
return function(y) {
return function(z) {
console.log(x * y * z);
return x * y * z;
};
};
};
例如
multiply(3,4,4) 转为 multiply(3)(4)(4)
将一个普通的多参数定义,如
function multiply(a,b,c){
return a*b*c
}
转为单参数函数多次调用
function multiply(a){
return function(b){
return function(c){
return a*b*c
}
}
}
使用ES6的写法就是
const multiply = a=>b=>c=>a*b*c
Function Currying
function curry(fn, ...args){
return args.length === fn.length ?
fn(...args) :
(...next_args) => curry(fn, ...args, ...next_args);
}
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
// 来晚了 ...
let total;
function a(m){
total = m;
return function(n){
return a(m*n)
}
}
a(3)(4)(4)
console.log(total) //48
const a = x => Object.assign(
y => a(x * y),
{
valueOf: () => x,
toString: () => String(x),
}
)
a(3)(4)(4) == 48 // ==> true
String(a(3)(4)(4)) // ==> "48"
console.log(a(3)(4)(4)) // ==> f 48
固定3个参数的的柯里化。。。
const curry3 = fn=> a => b => c => fn(a,b,c);
const mutl3 = (a, b, c) => a * b * c;
const curried3 = curry3(mutl3);
let result = curried3(3)(4)(4);
console.log(result);
如果是更加通用的累乘,参数不定,就不能这么用了。
const curry = fn => {
let _args = [];
const _fn = (...args) => {
_args.push(...args);
return args.length >= 1 ? _fn : fn(..._args);
}
return _fn;
}
// 累乘
const multiplication = curry(function() {
return Array.prototype.reduce.call(arguments, (acc, val) => {
return acc * val;
}, 1);
});
let result = multiplication(3)(4)(4)();
console.log(result);
8 回答4.8k 阅读✓ 已解决
6 回答3.5k 阅读✓ 已解决
5 回答2.9k 阅读✓ 已解决
5 回答6.4k 阅读✓ 已解决
4 回答2.3k 阅读✓ 已解决
4 回答2.8k 阅读✓ 已解决
3 回答2.5k 阅读✓ 已解决
函数柯里化 了解一下?