一、什么是函数组合?
函数组合是将两个或多个函数组合以产生新函数的过程。
举例来说:
var f = (...args) => console.log(`函数f,参数: ${JSON.stringify(args)}`);
var g = (...args) => console.log(`函数g,参数: ${JSON.stringify(args)}`);
var h = (...args) => console.log(`函数h,参数: ${JSON.stringify(args)}`);
// 先调用f,接着调用g,再调用h
f(g(h(x)));
这样写的起来嵌套层数比较多,后期维护起来也比较困难。
如果改成这样,用起来就方便多了:
function compose() {}
componse(f, g, h)(x);
// compose 就是组合函数,作用是将多个函数组合起来,并返回一个新的函数
二、实现
如果函数的个数是固定的话,可以简单的实现一个版本:
// 参数是2个函数
function compose(f, g) {
return function(x) {
return f(g(x));
}
}
// 参数是3个函数
function compose(f, g, h) {
return function(x) {
return f(g(h(x)));
}
}
但是这样扩展起来就不灵活,所以我们需要动态的根据参数的个数修改一下:
// [函数组合](https://github.com/reduxjs/redux/blob/v3.7.2/src/compose.js)
function compose(...funcs) {
return funcs.reduce((a, b) => {
return (...args) => {
return a(b(...args));
};
});
}
function Parent() {
console.log(`Parent`);
}
function Son() {
console.log(`Son`);
}
function Children(...args) {
console.log(`Children`, args);
}
var props = { a: 1, b: 2 };
Parent(Son(Children(props))); // -> compose(f,g,h)(props)
// Children [ { a: 1, b: 2 } ]
// Son
// Parent
compose(Parent, Son, Children)(props);
从代码中可以看出, 使用reduce方法来进行迭代,将多个参数的函数组装起来。