詳解JS中的compose函數(shù)和pipe函數(shù)用法
compose函數(shù)可以將需要嵌套執(zhí)行的函數(shù)平鋪,嵌套執(zhí)行就是一個函數(shù)的返回值將作為另一個函數(shù)的參數(shù)。我們考慮一個簡單的需求:這個需求很簡單,直接一個計算函數(shù)就行:
const calculate = x => (x + 10) * 10;let res = calculate(10);console.log(res); // 200
但是根據(jù)我們之前講的函數(shù)式編程,我們可以將復雜的幾個步驟拆成幾個簡單的可復用的簡單步驟,于是我們拆出了一個加法函數(shù)和一個乘法函數(shù):
const add = x => x + 10;const multiply = x => x * 10;// 我們的計算改為兩個函數(shù)的嵌套計算,add函數(shù)的返回值作為multiply函數(shù)的參數(shù)let res = multiply(add(10));console.log(res); // 結果還是200
上面的計算方法就是函數(shù)的嵌套執(zhí)行,而我們compose的作用就是將嵌套執(zhí)行的方法作為參數(shù)平鋪,嵌套執(zhí)行的時候,里面的方法也就是右邊的方法最開始執(zhí)行,然后往左邊返回,我們的compose方法也是從右邊的參數(shù)開始執(zhí)行,所以我們的目標就很明確了,我們需要一個像這樣的compose方法:
// 參數(shù)從右往左執(zhí)行,所以multiply在前,add在后let res = compose(multiply, add)(10);
在講這個之前我們先來看一個需要用到的函數(shù)Array.prototype.reduce
Array.prototype.reduce數(shù)組的reduce方法可以實現(xiàn)一個累加效果,它接收兩個參數(shù),第一個是一個累加器方法,第二個是初始化值。累加器接收四個參數(shù),第一個是上次的計算值,第二個是數(shù)組的當前值,主要用的就是這兩個參數(shù),后面兩個參數(shù)不常用,他們是當前index和當前迭代的數(shù)組:
const arr = [[1, 2], [3, 4], [5, 6]];// prevRes的初始值是傳入的[],以后會是每次迭代計算后的值const flatArr = arr.reduce((prevRes, item) => prevRes.concat(item), []);console.log(flatArr); // [1, 2, 3, 4, 5, 6]Array.prototype.reduceRight
Array.prototype.reduce會從左往右進行迭代,如果需要從右往左迭代,用Array.prototype.reduceRight就好了
const arr = [[1, 2], [3, 4], [5, 6]];// prevRes的初始值是傳入的[],以后會是每次迭代計算后的值const flatArr = arr.reduceRight((prevRes, item) => prevRes.concat(item), []);console.log(flatArr); // [5, 6, 3, 4, 1, 2]
那這個compose方法要怎么實現(xiàn)呢,這里需要借助Array.prototype.reduceRight:
const compose = function(){ // 將接收的參數(shù)存到一個數(shù)組, args == [multiply, add] const args = [].slice.apply(arguments); return function(x) { return args.reduceRight((res, cb) => cb(res), x); }}// 我們來驗證下這個方法let calculate = compose(multiply, add);let res = calculate(10);console.log(res); // 結果還是200
上面的compose函數(shù)使用ES6的話會更加簡潔:
const compose = (...args) => x => args.reduceRight((res, cb) => cb(res), x);
Redux的中間件就是用compose實現(xiàn)的,webpack中l(wèi)oader的加載順序也是從右往左,這是因為他也是compose實現(xiàn)的。
pipe函數(shù)pipe函數(shù)跟compose函數(shù)的左右是一樣的,也是將參數(shù)平鋪,只不過他的順序是從左往右。我們來實現(xiàn)下,只需要將reduceRight改成reduce就行了:
const pipe = function(){ const args = [].slice.apply(arguments); return function(x) { return args.reduce((res, cb) => cb(res), x); }}// 參數(shù)順序改為從左往右let calculate = pipe(add, multiply);let res = calculate(10);console.log(res); // 結果還是200
ES6寫法:
const pipe = (...args) => x => args.reduce((res, cb) => cb(res), x)
以上就是詳解JS中的compose函數(shù)和pipe函數(shù)用法的詳細內(nèi)容,更多關于JS的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
