JS 函数式概念:Pipe 和 Compose

2025-06-07

JS 函数式概念:Pipe 和 Compose

函数管道和组合是函数式编程中的概念,当然在 JavaScript 中也是可能的 - 因为它是一种多范式编程语言 - 让我们快速深入了解这个概念。

其概念是按照给定的顺序执行多个函数,并将一个函数的结果传递给下一个函数。

你可以这样做:



function1(function2(function3(initialArg)))


Enter fullscreen mode Exit fullscreen mode

或者使用函数组合



compose(function3, function2, function1)(initialArg);


Enter fullscreen mode Exit fullscreen mode

或功能管道



pipe(function1, function2, function3)(initialArg);


Enter fullscreen mode Exit fullscreen mode

简而言之,组合和管道几乎相同,唯一的区别在于执行顺序;如果函数从左到右执行,则它是管道,另一方面,如果函数从右到左执行,则它称为组合。

更准确的定义是:“在函数式编程中,Compose 是一种将较小的单元(我们的函数)组合成更复杂的东西(你猜对了,另一个函数)的机制”。

以下是管道函数的示例:



const pipe = (...functions) => (value) => {
    return functions.reduce((currentValue, currentFunction) => {
      return currentFunction(currentValue);
    }, value);
  };


Enter fullscreen mode Exit fullscreen mode

让我们对此增加一些见解:

基础知识

  • 我们需要收集 N 个函数
  • 也选择一个论点
  • 以链式方式执行它们,将收到的参数传递给将要执行的第一个函数
  • 调用下一个函数,并将第一个函数的结果作为参数添加。
  • 对数组中的每个函数继续执行相同的操作。


/* destructuring to unpack our array of functions into functions */
const pipe = (...functions) => 
  /* value is the received argument */
  (value) => {
    /* reduce helps by doing the iteration over all functions stacking the result */
    return functions.reduce((currentValue, currentFunction) => {
      /* we return the current function, sending the current value to it */
      return currentFunction(currentValue);
    }, value);
  };


Enter fullscreen mode Exit fullscreen mode

我们已经知道,如果箭头函数返回单个语句,则它不需要括号或返回标签,因此我们可以通过像这样编写来节省键盘点击次数:



const pipe = (...functions) => (input) => functions.reduce((chain, func) => func(chain), input);


Enter fullscreen mode Exit fullscreen mode

如何使用



const pipe = (...fns) => (input) => fns.reduce((chain, func) => func(chain), input);

const sum = (...args) => args.flat(1).reduce((x, y) => x + y);

const square = (val) => val*val; 

pipe(sum, square)([3, 5]); // 64


Enter fullscreen mode Exit fullscreen mode

请记住,第一个函数是左边的函数(管道),所以 3 + 5 = 8,8 的平方是 64。我们的测试进展顺利,一切似乎都运行良好,但如果必须链接async函数怎么办?

异步函数上的管道

我的一个用例是使用一个中间件来处理客户端和网关之间的请求,该过程始终相同(执行请求、错误处理、选择响应中的数据、处理响应以烹饪一些数据等等),因此看起来很有魅力:



export default async function handler(req, res) {
  switch (req.method) {
    case 'GET':
      return pipeAsync(provide, parseData, answer)(req.headers);
     /* 
       ... 
     */ 


Enter fullscreen mode Exit fullscreen mode

让我们看看如何在 Javascript 和 Typescript 中处理异步函数管道:

JS 版本



export const pipeAsync =
  (...fns) =>
  (input) =>
    fns.reduce((chain, func) => chain.then(func), Promise.resolve(input));


Enter fullscreen mode Exit fullscreen mode

添加 JSDoc 类型使其更易于理解(我猜)



/**
 * Applies Function piping to an array of async Functions.
 * @param  {Promise<Function>[]} fns
 * @returns {Function}
 */
export const pipeAsync =
  (...fns) =>
  (/** @type {any} */ input) =>
    fns.reduce((/** @type {Promise<Function>} */ chain, /** @type {Function | Promise<Function> | any} */ func) => chain.then(func), Promise.resolve(input));


Enter fullscreen mode Exit fullscreen mode

TS 版本



export const pipeAsync: any =
  (...fns: Promise<Function>[]) =>
  (input: any) =>
    fns.reduce((chain: Promise<Function>, func: Function | Promise<Function> | any) => chain.then(func), Promise.resolve(input));


Enter fullscreen mode Exit fullscreen mode

这样,它将适用于异步和非异步函数,因此它比上面的示例更胜一筹。

您可能对函数组合感到好奇,让我们来看看:

函数组合

如果你更喜欢从右到左调用函数,那么只需要改变reduceforredureRight就可以了。让我们看看函数组合的异步方式:



export const composeAsync =
  (...fns) =>
  (input) =>
    fns.reduceRight((chain, func) => chain.then(func), Promise.resolve(input));


Enter fullscreen mode Exit fullscreen mode

回到上面的例子,让我们复制相同的内容,但进行组合:

如何使用



const compose = (...fns) => (input) => fns.reduceRight((chain, func) => func(chain), input);

const sum = (...args) => args.flat(1).reduce((x, y) => x + y);

const square = (val) => val*val; 

compose(square, sum)([3, 5]); // 64


Enter fullscreen mode Exit fullscreen mode

请注意,我们颠倒了函数顺序,以使其与帖子顶部的示例保持一致。

现在,将首先调用 sum(位于最右边的位置),因此 3 + 5 = 8,然后 8 的平方等于 64。


如果您有任何问题或建议,请在下面评论

文章来源:https://dev.to/joelbonetr/js-function-concepts-pipe-and-compose-1mho
PREV
使用 JavaScript 进行语音识别
NEXT
CSS 最佳实践和给初学者的建议 CSS / SCSS 最佳实践