函数实现 composeFunctions(fn1,fn2,fn3,fn4)等价于fn4(fn3(fn2(fn1))

  • 函数组合运行
  • 说明:实现一个方法,可将多个函数方法按从左到右的方式组合运行。
  • composeFunctions(fn1,fn2,fn3,fn4)等价于fn4(fn3(fn2(fn1))
  •  1 const add = x => x + 1;
     2 const multiply = (x, y) => x * y;
     3 const multiplyAdd = composeFunctions(multiply, add);
     4 
     5 function composeFunctions() {
     6     var args = Array.prototype.slice.apply(arguments);
     7     console.log('args',args)
     8     return function() {
     9         if (args.length == 1) {
    10             console.log('args=1',this)
    11             return args[0].apply(this, Array.prototype.slice.apply(arguments));
    12 
    13         }
    14         console.log('args!=1',args)
    15         return composeFunctions(...args.slice(1))(args[0].apply(this, Array.prototype.slice.apply(arguments)));
    16     }
    17 }
    18 console.log(multiplyAdd(3, 4));// 返回 13

猜你喜欢

转载自www.cnblogs.com/xfcao/p/12339655.html