理解组合函数

KooTeam / 2023-08-21 / 原文

理解组合函数

组合(Compose)函数是在JavaScript开发过程中一种对函数的使用技巧、模式:

口比如我们现在需要对某一个数据进行函数的调用,执行两个函数fn1和fn2,这两个函数是依次执行的;

口那么如果每次我们都需要进行两个函数的调用,操作上就会显得重复;

口那么是否可以将这两个函数组合起来,自动依次调用呢?

口这个过程就是对函数的组合,我们称之为组合函数(Compose Function);

实现最简单的组合函数

 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))