柯里化的简单实现
Q1:柯里化干嘛的?
P:讲一个函数进行封装,传递给该函数的参数可以分多次进行传递
例如:
let fn = curry(function (a, b, c) {
console.log("log--------", [a, b, c]);
return [a, b, c];
});
fn("a", "b", "c"); // ["a", "b", "c"]
fn("a", "b")("c"); // ["a", "b", "c"]
fn("a")("b")("c"); // ["a", "b", "c"]
fn("a")("b", "c"); // ["a", "b", "c"]
根据特点来进行实现的思路
1. 既然是讲一个函数封装后再返回一个函数,那我们可以得出
function curry(fn) {
return function () {
// 使用call来更改this指向问题
return fn.call(this);
};
}
2. 返回的函数可以进行传参,最后参数回传到一开始封装好的那个函数里面去
function curry(fn) {
return function (...args) {
// 使用call来更改this指向问题
return fn.call(this, ...args);
};
}
3. 在参数传递未满足函数参数的个数时,再返回一个函数让他接着传参,所以可以使用递归,知道他返回的参数够了之后才执行函数
function curry(fn, ...args2) {
const length = fn.length;
return function (...args) {
// 将所有的参数收集起来,传给函数中去
const allArgs = [...args2, ...args];
if (allArgs.length < length) {
return curry.call(this, fn, ...allArgs);
}
return fn.call(this, ...allArgs);
};
}