js中Compose函数实现扁平化

1 篇文章 0 订阅

js实现扁平化思想

// 将前一个函数的结果作为初始值带入下一个函数中,实现函数的扁平化

function compose(...funcs) { //...func为传入的函数
    return function proxy(...args) {//...args为第一次调用函数所传入的参数
        let len = funcs.length;
        if (len === 0) {
            return args;
        } else if (len === 1) {
            return funcs[0](...args);
        } else {
            return funcs.reduce((x, y) => {
                return typeof x === "function" ? y(x(...args)) : y(x)
            });
        }
    }
}
let fn1 = function (x) {
    return x + 10;
};
let fn2 = function (x) {
    return x * 10;
};
let fn3 = function (x) {
    return x / 10;
};
console.log(compose()(5));  //5
console.log(compose(fn1)(5)); //15
console.log(compose(fn1, fn2)(5));  //150 
console.log(compose(fn1, fn2, fn1, fn3)(5)); //16
// redux中的compose源码
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)));
}
console.log(compose()(5));  //5
console.log(compose(fn1)(5)); //15
console.log(compose(fn1, fn2)(5));  //60
console.log(compose(fn1, fn2, fn1, fn3)(5)); //115
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哆啦咪唏

看到这里了,不留下点什么吗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值