Most of Effect's functions center around the first argument being the Effect or 'data' to be worked on. However, this can lead to readability issues when calling multiple functions in a row.
Take these 3 simple functions:
const increment = (x: number) => x + 1
const double = (x: number) => x * 2
const subtractTen = (x: number) => x - 10If we only needed to use 1 there are not really any problems with readability:
const result = increment(5);However, as we increase the amount of functions we pass our data through things can get messy:
const result = subtractTen(double(increment(5)));Now we have to read from the inside -> out through multiple layers of nested function calls.
Thankfully there is an alternative: pipe
The pipe function takes a value and a series of functions, and then applies these functions one after the other, where the output of one function serves as the input to the next function, eventually resulting in a final output.
pipe(z, y, x) === x(y(z))big tooltip
pipe is never required, it only represents syntactic sugar over the exact same resulting function calls
Finally, lets look at our previous code but using pipe
const result = pipe(
5,
increment,
double,
subtractTen
)Much more readable. Now we can clearly see the flow from the initial data through each function:
- Start with 5
- Increment it
- Double that result
- Subtract 10 from that result