compose函數(shù)
1.將需要嵌套執(zhí)行的函數(shù)平鋪
2.嵌套執(zhí)行指的是,一個(gè)函數(shù)的返回值將作為另一個(gè)函數(shù)的參數(shù)
實(shí)現(xiàn)函數(shù)式編程中的Pointfree滤馍,使我們專注于轉(zhuǎn)換而不是數(shù)據(jù)
像下面這段簡(jiǎn)單的代碼:
let calculate = x => (x + 10) * 10;
console.log(calculate(10));
也可以像下面這樣寫:
let add = x => x + 10;
let multiply = y => y * 10;
console.log(multiply(add(10)));
提高代碼的復(fù)用性鹦肿,則可以如下:
let add = x => x + 10;
let multiply = y => y * 10;
let compose = (f,g) => {
return function(x){
return(f(g(x)));
}
}
let calculate = compose(multiply,add);
console.log(calculate(10));
而想要多個(gè)函數(shù)嵌套運(yùn)算黑滴,實(shí)現(xiàn)通用的compose函數(shù)真友,則可以如下:
let add = x => x + 10;
let multiply = y => y * 10;
let compose = function(){
let args = [].slice.call(arguments);
return function(x){
return args.reduceRight(function(res, cb){
return cb(res);
},x)
}
}
let calculate = compose(multiply,add);
console.log(calculate(10));
更簡(jiǎn)便的寫法捍岳,如下:
let add = x => x + 10;
let multiply = y => y * 10;
//es6寫法
const compose = (...args) => x => args.reduce((res, cb) => cb(res), x);
let calculate = compose(multiply,add);
console.log(calculate(10));
compose函數(shù)的執(zhí)行方向是從右往左執(zhí)行芋哭,而pipe函數(shù)則相反
pipe函數(shù)
let add = x => x + 10;
let multiply = y => y * 10;
//es6寫法
const compose = (...args) => x => args.reduceLeft((res, cb) => cb(res), x);
let calculate = compose(multiply,add);
console.log(calculate(10));