美文网首页
用reduce一句话实现函数式编程 组合函数 pipe, com

用reduce一句话实现函数式编程 组合函数 pipe, com

作者: 上帝说有bug | 来源:发表于2021-11-02 13:56 被阅读0次
const pipe =
  (...args) =>
  params =>
    args.reduce((pre, next) => next(pre), params);

const compose =
  (...args) =>
  params =>
    args.reverse().reduce((pre, next) => next(pre), params);

const pipePromise = (...args) => {
  const init = args.pop();
  return (...arg) =>
    args.reduce(
      (sequence, func) => sequence.then(result => func.call(null, result)),
      Promise.resolve(init.apply(null, arg)),
    );
};

const composePromise = (...args) => {
  const init = args.pop();
  return (...arg) =>
    args
      .reverse()
      .reduce(
        (sequence, func) => sequence.then(result => func.call(null, result)),
        Promise.resolve(init.apply(null, arg)),
      );
};

export { pipe, compose, pipePromise, composePromise };

相关文章

网友评论

      本文标题:用reduce一句话实现函数式编程 组合函数 pipe, com

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