JavaScript中使用compose对函数进行编排

reduce方法介绍

开始之前先介绍下reduce函数的使用。reduce是数组的一个高阶方法,用来遍历数组的每一项实现累加

var arr = ['a','b','c'];
var str = arr.reduce((total, item) => total + item); //abc

total初始值默认为数组的第一项,还可以通过reduce的第二个参数给total设置初始值

var arr = ['a','b','c'];
var str = arr.reduce((total, item) => total + item,'s'); //sabc

使用reduce进行函数的编排

使用compose计算商品的价格:

    //商品打折函数 假设0.8折
	function discount(total){
	 return total * 0.8;
	};
	//商品总价 假设购买10件
	function totalPrice(total){
	 return total * 10;
	};
	//运费 假设12元
	function express(total){
	  return total + 12;
	};
	
	const compose = (fns) => (price) => fns.reduce((total, item) => item(total), price);
	let p= compose([totalPrice, discount, express])(100); //812  

redux的compose

再来看redux中的compose

	function compose(fns){
	  return fns.reduce((total, item) => (...args) => total(item(args)));
	}
	let p = compose([totalPrice, discount, express])(100); //896.0000000000001

要注意执行顺序跟函数列表是相反的,相当于totalPrice(discount(express(100)));

koa中的compose

    //koa的compose
    function compose(fns) {
      var result;
      return function (ctx) {
        var i = 0;
        function dispatch(i, ctx) {
          if (i === fns.length) {
            result = ctx;
            return;
          };
          var fn = fns[i];
          return fn(ctx, dispatch.bind(null, ++i));
        };
        dispatch(0, ctx);
        return result;
      };
    };
    let p1 = compose([totalPrice, discount, express])(100); //812  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值