函数编程的函数组合:两个纯函数组合之后返回了一个新函数
var compose = function(f,g) { return function(x) { return f(g(x)); }; };
效果:
var toUpperCase = function(x) { return x.toUpperCase(); }; var exclaim = function(x) { return x + "!"; }; var shout = compose( exclaim, toUpperCase ); console.log(shout("hello world")); //HELLO WORLD!
函数组合可以避免在实现相同需求式而使用嵌套函数,实现可读性。
实现一组函数的叠加产生一个新的函数我们可以利用reduce来实现,利用reduce 的累加的特性实现函数的嵌套。
function comp1(arr) { return function(val) { return arr.reduce(function(x, y) { return y(x(val)); }); }; }
或者
function comp2(arr) { return function(val) { return arr.reduce(function(x, y) { return y(x); },val); }; }
这里把需要组合的函数赋值给一个数组,然后返回一个函数对数组里的函数进行组合后的函数
例子:
var funArr = [toUpperCase, exclaim]; console.log(comp1(funArr)); // function...
console.log(comp1(funArr)("hello")); // HELLO!
console.log(comp2(funArr)); // function...
console.log(comp2(funArr)("hello")); // HELLO!