-
柯里化 curry
参考lodash 4.17.11 API 实现
- 使用bind拼接参数
function curry(fn) {
const { length } = fn;
return function next() {
if (length === arguments.length) {
return fn.apply(this, arguments);
} else if (arguments.length < length) {
return next.bind(this, ...arguments);
}
};
}
function abc(a, b, c) {
return [a, b, c];
}
const curried = curry(abc);
console.info(curried(1)(2)(3)); //[1,2,3]
console.info(curried(1, 2)(3)); //[1,2,3]
console.info(curried(1, 2, 3)); //[1,2,3]
- 使用闭包将变量保存在curry函数中的container变量
function curry(fn) {
const { length } = fn;
let container = [];
return function next() {
const args = Array.prototype.slice.call(arguments);
container = container.concat(args);
if (length === container.length) {
const ret = fn.apply(this, container);
container = [];// 此处需要将保存参数的容器清空,连续调用curried函数,container参数不断增加
return ret;
} else if (container.length < length) {
return next;
}
};
}
function abc(a, b, c) {
return [a, b, c];
}
const curried = curry(abc);
console.info(curried(1)(2)(3)); //[1,2,3]
console.info(curried(1, 2)(3)); //[1,2,3]
console.info(curried(1, 2, 3)); //[1,2,3]
网友评论