定义
Function Composition 是把两个或多个方法合成为一个新方法的过程
Function composition is the process of combining two or more functions to produce a new function. Composing functions together is like snapping together a series of pipes for our data to flow through.
实例
一个常见需求:把下面数组中所有的 type 为 Household 的找出来,计算他们的 price 总和
1 | const expenses = [ |
使用 Pure Function + Pure Function 我们这样处理
1 | const typeHousehold = function(arr) { |
我们也可以使用 Function Composition
1 | const typeHousehold = function(arr) { |
compose 函数如果用 es6 写的话,更佳简洁
1 | const compose = (f, g) => x => g(f(x)); |
工具库
lodash 提供了 .flow 和 .flowRight 方法来获得一个合成过的方法
1 | const sumAllHousehold = _.flow([typeHousehold, sumAll]); // 从左到右 |
Ramda 也提供了 R.compose 方法
1 | const sumAllHousehold = R.compose(sumAll, typeHousehold); |