js函數(shù)庫(kù)里化主要作用是將一個(gè)包含多個(gè)參數(shù)的函數(shù)轉(zhuǎn)換成只包含一個(gè)參數(shù)的函數(shù)并返回筐付。例如:
function add (n1, n2, n3){
return n1 + n2 + n3;
}
function curryAdd(n1){
return function (n2) {
return function (n3) {
return n1 + n2 + n3;
}
}
}
這么做有什么好處只估,其實(shí)就是為了通過復(fù)用參數(shù)來(lái)復(fù)用函數(shù):
function request(method, url, params){
return fetch(url, {
method: method,
...
})
}
// currying
function postRequest(){
return function(url, params){
return fetch(url, {
method: GET,
body: params
})
}
}
怎么實(shí)現(xiàn)函數(shù)庫(kù)里化:
function curry(fn){
const args = Array.prototype.slice.call(arguments, 1);
return function(){
const _args = Array.prototype.slice.call(arguments);
const all = args.concat(_args);
if(all.length < fn.length){
return curry.call(this, fn, ...all)
}
return fn.apply(this, all);
}
}
function add(n1, n2, n3){
return n1 + n2 + n3;
}
curry(add)(1)(2)(3); // 6