js compose function combination [handwritten code]

composeFunction is a method of function composition, which allows multiple functions to be combined and executed sequentially from right to left. The advantage of this approach is that functions can be combined from right to left, making the code more concise and allowing multiple functions to share a single parameter.

Handwritten compose:

const compose = function(...funcs) {
    
    
      // 计算函数的个数
      let len = funcs.length
      // 初始化函数调用次数
      let index = 0
      // 初始化最终返回的结果
      let result
      // 返回一个函数,用于接收实际参数
      return function (...args){
    
    
          // 循环执行所有的函数
          for(let i=0;i<len;i++){
    
    
               // 判断是否是第一次执行,如果是第一次执行则直接执行
               if(i==0) {
    
    
                  result=funcs[0](...args)
               } else{
    
    
                  // 如果不是第一次执行,则把上一次的结果当做参数传给下一个函数
                  result = funcs[i](result)
               }
           }
          // 返回最终的结果
          return result 
      }
    }
function fn1(a){
    
    
    return a+1
  }
  function fn2(b){
    
    
    return b+2
  }
  function fn3(c){
    
    
    return c+3
  }

  const fn =compose(fn1,fn2,fn3)
  let res = fn(10)
  console.log(res); //16

Guess you like

Origin blog.csdn.net/m0_61696809/article/details/129353687