// 普通函数柯里化
// 函数柯里化,只传递给函数一部分参数来调用它,让它返回一个函数去处理剩下的参数
{
// 参数固定的柯里化
function funToCurry (fn, ...args) {
return function (...argums) {
let argCom = [...args, ...argums];
if (argCom.length < fn.length) {
return funToCurry.call(null, fn, ...argCom);
} else {
return fn.apply(null, argCom);
}
}
}
function add (a, b, c, d) {
return a + b + c + d;
}
let addToCurry = funToCurry(add);
console.log(addToCurry(1)(2)(3)(4));
console.log(addToCurry(1, 2)(3)(4));
console.log(addToCurry(1)(2, 3)(4));
}
{
// 参数不固定的柯里化
function funToCurry2 (fn, ...args) {
return function (...argums) {
let argCom = [...args, ...argums];
if (argums.length !== 0) {
return funToCurry2.call(null, fn, ...argCom);
} else {
return fn.apply(null, argCom);
}
}
}
function add2 (...args) {
if (args.length === 0) {
return 'no-data';
} else {
return args.map(item => 'data-' + item);
}
}
let addToCurry = funToCurry2(add2);
console.log(addToCurry(1)(2)(3)(4)());
console.log(addToCurry(1, 2)(3)());
console.log(addToCurry(1)());
console.log(addToCurry());
}
{
// 函数反柯里化
function curryToFun(fn) {
return function (...args) {
let tempFun = fn;
for (let i = 0; i < args.length; i++) {
tempFun = tempFun.call(null, args[i]);
}
return tempFun;
}
}
function curry (a) {
return function (b) {
return function (c) {
return function (d) {
return a + b + c + d;
}
}
}
}
let curryToAdd = curryToFun(curry);
console.log(curryToAdd(1, 2, 3, 4));
console.log(curryToAdd(3, 4, 6, 7));
}
网友评论