# 如何用一行代码实现 compose 函数

Issue

欢迎在 Issue 中交流与讨论: Issue 182 (opens new window)

Author

回答者: LRQLRQ (opens new window)

function compose() {

  let fns = [...arguments];

  return function() {
    let args = [...arguments];
    let result = fns.reduce((ret, fn) => {
      ret = fn.apply(this, ret);
      return Array.isArray(ret) ? ret : [ret];
    }, args);
    
    return result;
  }
}

let toUpperCase = (x) => x.toUpperCase();
let exclaim = (x) => x + '!';
let shout = compose(toUpperCase,exclaim);
let str = shout('hello world');
console.log(str);

第一次试着写,简单查了一下compose是什么意思,竟然拼凑出来了。请各位指正。 😄

Last Updated: 1/17/2021, 2:02:56 PM