函数管道和组合是来自函数式编程的概念,它们在 JavaScript 中当然是可能的——因为它是一种多范式编程语言——让我们快速深入了解这些概念。
这个概念是以给定的顺序执行多个函数,并将一个函数的结果传递给下一个函数。
你可以这样做丑陋的:
function1(function2(function3(initialArg)))
或者使用函数组合
compose(function3, function2, function1)(initialArg);
或功能管道
pipe(function1, function2, function3)(initialArg);
简而言之,组成和管道几乎相同,唯一的区别是执行顺序; 如果函数是从左到右执行的,它就是一个管道,另一方面,如果函数是从右到左执行的,它就是 compose。
更准确的定义是:“在函数式编程中,Compose 是一种将较小的单元(我们的函数)组合成更复杂的东西(你猜对了,另一个函数)的机制”。
下面是一个管道函数的例子:
const pipe = (...functions) => (value) => {
return functions.reduce((currentValue, currentFunction) => {
return currentFunction(currentValue);
}, value);
};
让我们对此添加一些见解:
基本
我们需要收集 N 个函数
也选择一个论点
链式执行它们,将接收到的参数传递给将要执行的第一个函数
调用下一个函数,将第一个函数的结果作为参数添加。
继续对数组中的每个函数执行相同的操作。
const pipe = (...functions) =>
/* 值是接收到的参数 */
(value) => {
/* reduce 通过对所有函数进行迭代来帮助堆叠结果 */
return functions.reduce((currentValue, currentFunction) => {
/* 我们返回当前函数,将当前值发送给它*/
return currentFunction(currentValue);
}, value);
};
我们已经知道箭头函数不需要括号,如果它们返回单个语句则不需要返回标记,所以我们可以这样写来节省键盘点击:
const pipe = (...functions) => (input) => functions.reduce((chain, func) => func(chain), input);
如何使用
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
请记住,第一个函数是左边的函数(Pipe),所以 3+5 = 8 和 8 的平方是 64。我们的测试进行得很顺利,一切似乎都工作正常,但是必须链接异步函数怎么办?
异步函数上的管道
我的一个用例是有一个中间件来处理客户端和网关之间的请求,过程总是相同的(执行请求、错误处理、选择响应中的数据、处理响应以烹饪一些 数据等等),所以让它看起来像这样是一种魅力:
export default async function handler(req, res) {
switch (req.method) {
case 'GET':
return pipeAsync(provide, parseData, answer)(req.headers);
/*
...
*/
让我们看看如何在 Javascript 和 Typescript 中处理异步函数管道:
JS版本
export const pipeAsync =
(...fns) =>
(input) =>
fns.reduce((chain, func) => chain.then(func), Promise.resolve(input));
添加了 JSDoc 类型以使其更易于理解(我猜)
/**
* 将函数管道应用于异步函数数组。
* @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));
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));
这样,它既适用于异步功能,也适用于非异步功能,因此它比上面的示例更胜一筹。
您可能想知道函数组合如何,所以让我们看一下:
功能组合
如果您更喜欢从右到左调用函数,则只需将 reduce 更改为 redureRight 就可以了。 让我们看看函数组合的异步方式:
export const composeAsync =
(...fns) =>
(input) =>
fns.reduceRight((chain, func) => chain.then(func), Promise.resolve(input));
回到上面的示例,让我们复制相同但具有组合的示例:
如何使用
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;
pipe(square, sum)([3, 5]); // 64
请注意,我们颠倒了函数顺序以使其与帖子顶部的示例保持一致。
现在,sum(位于最右边的位置)将首先被调用,因此 3+5=8 然后 8 的平方是 64。