compose 源码
先来看一下compose的源码官网源码
/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* (...args) => f(g(h(...args))).
*/
export default function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg
}
if (funcs.length === 1) {
return funcs[0]
}
return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
从这里我们知道实际上调用的数组的reduce方法;
在理解compose函数之前先来认识下什么是reduce方法?
reduce 方法
reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
- 语法
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
- 参数
- callback
执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:- accumulator
累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(见于下方)。 - currentValue
数组中正在处理的元素。 - index 可选
数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则从索引1起始。 - array可选
调用reduce()的数组
- accumulator
- initialValue可选
作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。
- 案例
- 累计求和
var sum = [0, 1, 2, 3].reduce(function (a, b) {
return a + b;
}, 0);
// sum 值为 6
存在一个数组 ,元素项为: 0,1,2,3,初始值为0;其中a参数为accumulator,也就是累计值的变量;最后的0;表示initialValue;
- 字符计数
var series = ['a1', 'a3', 'a1', 'a5', 'a7', 'a1', 'a3', 'a4', 'a2', 'a1'];
var result = series.reduce(function(accumulator,currentValue){
if(currentValue in accumulator){
accumulator[currentValue]++;
}else{
accumulator[currentValue] = 1;
}
return accumulator;
},{})
console.log(JSON.stringify(result));
// {"a1":4,"a3":2,"a5":1,"a7":1,"a4":1,"a2":1}
compose 函数
- 案例
import { compose } 'redux';
// function f
const f1 = (arg) => `函数f(${arg})`
// function g
const g2 = (arg) => `函数g(${arg})`
// function h 最后一个函数可以接受多个参数
const h3 = (...arg) => `函数h(${arg.join('_')})`
console.log(compose(f1,g2,h3)('a', 'b', 'c')) //函数f1(函数g2(函数h3(a_b_c)))
- 总结:compose函数最终会返回以最后的参数为最后一个函数的参数项依次累加函数。调用方法依次从最里面的参数到最外面的参数依次调用;