compose 组合函数的实现

所谓的 组合函数就是 把多层函数的调用 【f(gh(x))】【f,g,h 为三个函数】变成=》 F(f,g,h)(x) 这中便于阅读的格式 。

最简洁代码:

function compose(...funcs) {
    if (funcs.length === 0) {
        return arg => arg;
    }
 
    if (funcs.length === 1) {
        return funcs[0];
    }
 
    return funcs.reduce( (a, b) => (...args) => a(b(...args))  )
//很多 时候,递归都是可以用 reduce 实现的!!!

const add1 = (x) => x + 1;
const mul3 = (x) => x * 3;
const div2 = (x) => x / 2;
console.log(div2(mul3(add1(add1(0)))),'wu~~~~~~~~~~~~~~');
div2(mul3(add1(add1(0)))); //=>3
console.log(compose(div2,mul3,add1,add1)(0),'wuwu~~~~~~~~~~~~~~~~~~~~')
 
原文地址:https://www.cnblogs.com/Hijacku/p/14927265.html