pipe 从左到右组合函数 结构化一系列事件
You already compose functions. Pipe lets you compose by flowing them left-to-right, improving readability.
So far we’ve learned about HOFs, data-last functions, currying, and point-free style. What do they all tie back to?
Function Composition.
Their entire existence is to make composition easier for us. That fact becomes even more obvious when your functions perform multiple steps involving data.
中间变量 改造为pipe
Let’s revisit the first exercise from our Function Composition section: uppercase and reverse Bobo’s name. A broken-up solution would look something like this
支离破碎的解决方案
const getFirstName = (user) => {...}
const uppercaseString = (string) => {...}
const reverseString = (string) => {...}
const upperAndReverseFirstName = (user) => {
const name = getFirstName(user);
const uppercasedName = uppercaseString(name);
return reverseString(uppercasedName);
};
See how we need those intermediate variables to track the result as it goes through our function?
看看我们如何需要这些中间变量来跟踪通过函数的结果?
more complex === more variables
The more steps your function has, the more of those variables you’ll need. It becomes noisy and limits how declarative your code can be.
You could try nesting them, but I think that looks worse
函数的步骤越多,需要的变量就越多。
它变得嘈杂,限制了代码的声明性。
你可以试着给它们筑巢,但我认为那看起来更糟
const upperAndReverseFirstName = (user) => (
reverseString(uppercaseString(getFirstName(user)));
);
How about this?
使用pipe
import { pipe } from 'ramda';
const upperAndReverseFirstName = pipe(
getFirstName,
uppercaseString,
reverseString
);
const result = upperAndReverseFirstName({
firstName: 'Bobo'
});
console.log({ result });
pipe lets you compose functions from left-to-right, structuring them like a sequence of events. The leftmost function runs first, then passes its output to the next function and so on.
管道允许您从左到右组合函数,将其结构化为一系列事件。
最左边的函数首先运行,然后将其输出传递给下一个函数,依此类推。 结果是一个列表,非常类似于您在头脑风暴解决方案时编写的规范 取名字 大写 倒过来
The result is a list that closely resembles the spec you’d write up when brainstorming a solution
- Get the first name
- Uppercase it
- Reverse it
See the resemblance? Here’s an animation of that code, with Bobo running through it.pipe(
getFirstName,
uppercaseString,
reverseString
)
看到相似之处了吗?下面是该代码的动画,Bobo在其中运行。
Here’s another interactive example. We’re transforming a number.
```javascript import { pipe } from ‘ramda’;
const doMath = pipe( // double (x) => x * 2,
// triple (x) => x * 3,
// square (x) => x * x,
// increment (x) => x + 1 );
const result = doMath(2);
console.log({ result });
```