函数合成(compose)的多种实现原理

machinist

// 责任链模型(一个接一个执行)

const fn1 = (x, y) => x + y;
const fn2 = (z) => z * z;

// 正常组合

const compose = (fn1, ...other) => (...args) => {
  let ret = fn1(...args);
  other.forEach(item => {
    ret = item(ret);
  });
  return ret;
}

// redux 中间件组合方式

const reduxCompose = (...fns) => fns.reduce((a, b) => (...args) => b(a(...args)))

const fn = reduxCompose(fn1, fn2);

console.log(fn(1, 2));

// 洋葱圈模型(一半一半执行)

const koaCompose = (middlewares) => {
  return function () {
    return dispatch(0);
    function dispatch(idx) {
      const fn = middlewares[idx];
      if (!fn) {
        return Promise.resolve();
      }
      return Promise.resolve(
        fn(function next() {
          return dispatch(idx + 1)
        })
      )
    }
  }
};

async function func1(next) {
  console.log("func1");
  await next();
  console.log("func1 end");
}
async function func2(next) {
  console.log("func2");
  await delay();
  await next();
  console.log("func2 end");
}
async function func3(next) {
  console.log("func3");
}
async function delay() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, 2000);
  })
}
const middlewares = [func1, func2, func3];
const finaFn = koaCompose(middlewares);
finaFn()
阅读 489

前端手札
零零散散的前端知识点!聚拢成一片,坚持自己的分享之路,一起来监督吧!

JavaScript、 react、 echarts、 umi使用者

451 声望
26 粉丝
0 条评论

JavaScript、 react、 echarts、 umi使用者

451 声望
26 粉丝
文章目录
宣传栏