理解组合函数
1 // 组合函数的理解 2 function double(num){ 3 return num*2 4 } 5 function square(num){ 6 return num**2 7 } 8 var count=10 9 var result=square(double(count)) 10 console.log(result) 11 //实现最简单的组合函数 12 function composeFn(m,n){ 13 return function(count){ 14 return n(m(count)) 15 } 16 } 17 var newFn=composeFn(double,square) 18 console.log(newFn(count))
通用的组合函数的实现
1 //通用的组合函数的实现 2 function hyCompose(...fns){ 3 var length=fns.length 4 for(var i=0;i<length;i++){ 5 if(typeof fns[i] !== 'function'){ 6 throw new TypeError('Expected arguments are functions') 7 } 8 } 9 function compose(...args){ 10 var index=0 11 var result=length?fns[index].apply(this,args):args 12 while(++index<length){ 13 result=fns[index].call(this,result) 14 } 15 return result 16 } 17 return compose 18 } 19 function double(num){ 20 return num*2 21 } 22 function square(num){ 23 return num**2 24 } 25 var count=10 26 var newFn=hyCompose(double,square) 27 console.log(newFn(count))