美文网首页程序员
compose - 代码聚合

compose - 代码聚合

作者: 申_9a33 | 来源:发表于2021-02-14 14:11 被阅读0次

假如有三个函数,每个函数的返回值作为其他函数的入参

  • 例如·
function f1(arg){
  return `f1${arg}`
}

function f2(arg){
  return `f2${arg}`
}

function f3(arg){
  return `f3${arg}`
}
  • 普通调用
console.log(f1(f2(f3("hello"))))

// => f3
// => f2
// => f1
// => f1f2f3hello
  • compose聚合成一个函数
function compose(...funcs){
  if(funcs.length === 0){
    return arg =>arg
  }

  if(funcs.length === 1){
    return funcs[0]
  }

  return funcs.reduce((a,b)=>(...args)=>a(b(...args)))
}

console.log(compose(f1,f2,f3)('hello'))

// => f3
// => f2
// => f1
// => f1f2f3hello
  • 加上日志,浅析执行过程
function compose(...funcs){
    if(funcs.length === 0){
      return arg =>arg
    }
  
    if(funcs.length === 1){
      return funcs[0]
    }
  
    return funcs.reduce((a,b)=>{
        console.log(a,b,'1')
        return (...args)=>{
            console.log(a,b,'2')
            return a(b(...args))
        }
    })
  }
console.log(compose(f1,f2,f3))

// => [Function: f1] [Function: f2] 1
// => [Function (anonymous)] [Function: f3] 1
// => [Function (anonymous)]
  • 1.第一次执行 得到一个新函数 new1 = (args)=>f1(f2(args))
  • 2.第二次执行 得到第二个新函数 new2 = (args) => new1(f3(args))
  • 3.new2执行 new2('hello') => f3执行,并返回结果到 => new1执行,传入参数 => f2执行,返回结果 => f1执行,最终得到f1f2f3hello

相关文章

网友评论

    本文标题:compose - 代码聚合

    本文链接:https://www.haomeiwen.com/subject/pquyxltx.html