一、管道
当一个函数比较复杂时,可以把一个函数切分成多个小的函数,此过程中每一个小函数返回的结果,传入下一个函数,返回最终结果。
二、函数组合
组合函数:一个函数要经过多个函数处理才能得到最终值,这个时候可以把中间过程的函数合并成一个函数。
函数组合默认是从右到左执行默认从右开始执行
// 组合函数
function compose (f, g) {
return function (x) {
return f(g(x))
}
}
三、lodash 中的组合函数
lodash 中组合函数 flow() 或者 flowRight(),他们都可以组合多个函数
flow() 是从左到右运行
flowRight() 是从右到左运行,使用的更多一些
const _ = require('lodash')
const toUpper = s => s.toUpperCase()
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const f = _.flowRight(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))
四、lodash 的 flowRight 方法实现
// 多函数组合
function compose (...fns) {
return function (value) {
return fns.reverse().reduce(function (acc, fn) {
return fn(acc)
}, value)
}
}