超级面板
文章目录
最新文章
最近更新
文章分类
标签列表
文章归档

compose.js 源码阅读笔记

Composes functions from right to left..

接口

compose(…arguments)

  • arguments (Function): 需要进行函数合成的多个函数,每个函数接收单一的参数,它的返回值将作为一个参数提供给它左边的函数调用,而最右边的函数可以接收多个参数,而它的签名将会作为组合后返回函数的签名。
  • return (Function): 返回把所有的参数从右向左合成的结果

函数组合

组合是函数式编程的常用工具,我们在学习数学的时候会学到复合函数:

f(x) = 2 * x;
g(x) = x + 1;

(f ∘ g)(x) = f(g(x)) = 2 * (x + 1) = 2 * x + 2;

可以很容易把这个组合形式扩展到组合更多的函数上,而函数组合就是将多个函组合成单个的新的函数的过程:

var compose = function(f, g) {
return function(x) {
return f(g(x));
};
};

和层层嵌套的函数调用相比较,函数组合创建了一个从右向左的数据流,数据的处理和流向非常清晰。

源码注释

源代码如下:

/**
* 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))).
*
* 也就是说,组合实际上就是把 compose(f, g, h) 转换为 f(g(h(...args))) 其中...args 是 h 的参数
*/
export default function compose(...funcs) {
//没有参数返回一个不作任何变换的函数,即 f(x) = x ;
if (funcs.length === 0) {
return arg => arg
}

//只有一个函数参数,返回原参数
if (funcs.length === 1) {
return funcs[0]
}

//利用 reduceRight 从右向左组合函数
//reduceRight 和 reduce 类似,只不过是从数组结尾向开始方向合并
const last = funcs[funcs.length - 1]
const rest = funcs.slice(0, -1)
return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args))
}

相关

Redux 源码阅读笔记:

参考

本文阅读代码版本 3.5.2