Skip to content

Instantly share code, notes, and snippets.

@ethanniser
Last active June 23, 2023 17:26
Show Gist options
  • Save ethanniser/33843790fad9b6b47c93dc84b0ecfc1a to your computer and use it in GitHub Desktop.
Save ethanniser/33843790fad9b6b47c93dc84b0ecfc1a to your computer and use it in GitHub Desktop.

Pipe + "Data-First/Last"

Improving Readability of Multiple Function Calls

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 - 10

If 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

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment