Redux - compose源码解析

compose 其实比较FP,这也让我对以后看下haskell有点期待.缺少这种FP lib的运用

/**
* 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
} else {
const last = funcs[funcs.length - 1]
const rest = funcs.slice(0, -1)
return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args))
}
}

看下ramda里的例子,文字不好解释

var f = R.compose(R.inc, R.negate, Math.pow);

f(3, 4); // -(3^4) + 1

最后一个function先带入参数,然后依次带入相邻左侧的function