要素:
1、高阶函数:reduce;
2、处理函数:reducer;
3、数据:可以是具体数据、签名相同的普通函数、签名相同的高阶函数;
reduce(reducer, datas(data or funciton), initResult(optional))
一、平凡数据处理
1 In [5]: reduce(add, [1,2,3,4,5])
2 Out[5]: 15
1 In [6]: reduce(add, [1,2,3,4,5], 10)
2 Out[6]: 25
二、函数组作为数据、计算串联、函数输入与返回单一类型兼容;缩减结果为普通数值;
reducer:(result, fn) => fn(result)
function compose(...funcs) {
return result => [...funcs]
.reverse()
.reduce((result, fn) => fn(result), result);
}
三、函数组作为数据、计算串联组合,缩减的结果任然是一个函数;函数组签名一致,且输出与输入匹配;
funcs.reduce((a, b) => (...args) => a(b(...args)))
function compose(...funcs) {
return funcs
.reverse()
.reduce((fn1, fn2) => (...args) => fn2(fn1(...args)));
}
四、高阶函数组合,后面的函数作为前一高阶函数的参量输入,通过柯里化函数的局部赋值使函数组函数满足要求(next);
({ getState, dispatch }) => next => action
给({ getState, dispatch }) => next => action签名的函数组分步赋值并进行串联的过程;
整体上是dispatch的method swizzling;
export default function applyMiddleware(...middlewares) {
return (next) =>
(reducer, initialState) => {
var store = next(reducer, initialState);
var dispatch = store.dispatch;
var chain = [];
//构造初值
var middlewareAPI = {
getState: store.getState,
dispatch: (action) => dispatch(action)
};
//给柯里化函数赋初值:next => action
chain = middlewares.map(middleware => middleware(middlewareAPI));
//next
dispatch = compose(...chain, store.dispatch);
return {
...store,
dispatch
};
};
}