每日一题12/17之compose函数(闭包应用)

实现函数fn,让其具有如下功能(百度二面)

/* 
    在函数式编程当中有一个很重要的概念就是函数组合, 实际上就是把处理数据的函数像管道一样连接起来, 然后让数据穿过管道得到最终的结果。 例如:
    const add1 = (x) => x + 1;
    const mul3 = (x) => x * 3;
    const div2 = (x) => x / 2;
    div2(mul3(add1(add1(0)))); //=>3
​
    而这样的写法可读性明显太差了,我们可以构建一个compose函数,它接受任意多个函数作为参数(这些函数都只接受一个参数),然后compose返回的也是一个函数,达到以下的效果:
    const operate = compose(div2, mul3, add1, add1)
    operate(0) //=>相当于div2(mul3(add1(add1(0)))) 
    operate(2) //=>相当于div2(mul3(add1(add1(2))))
​
    简而言之:compose可以把类似于f(g(h(x)))这种写法简化成compose(f, g, h)(x),请你完成 compose函数的编写 
*/

两种做法:第一种是compose执行先得到一个函数,然后再根据参数个数选择返回值。

const compose = (...funcs) => {
    // funcs:未来需要执行的函数集合「执行顺序是从后到前」
    return x => {
        // x是执行第一个函数的初始实参值
        let len = funcs.length;
        if (len === 0) return x;
        if (len === 1) return funcs[0](x);
        // funcs -> [div2, mul3, add1, add1]
        return funcs.reduceRight((result, func) => {
            return func(result);
        }, x);
    };
};
const add1 = (x) => x + 1;
const mul3 = (x) => x * 3;
const div2 = (x) => x / 2;
const operate = compose(div2, mul3, add1, add1);
console.log(operate(0));

第二种方法,来自redux,先判断参数个数,再选择不同的函数处理。

function compose(...funcs) {
    if (funcs.length === 0) {
        return arg => {
            return arg;
        };
    }
    if (funcs.length === 1) {
        return funcs[0];
    }
    return funcs.reduce((a, b) => {
        return x => {
            return a(b(x));
        };
    });
}
const add1 = (x) => x + 1;
const mul3 = (x) => x * 3;
const div2 = (x) => x / 2;
const operate = compose(div2, mul3, add1, add1);
console.log(operate(0));
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值