Nick Scialli • April 19, 2021 • 🚀 3 minute read
What is Piping?
Piping is taking the output of one function and sending it directly into another function. In pseudocode, this can be represented as:
output = input -> func1 -> func2 -> func3
In this case, the
input is piped into
func1, the output of of
func1 is piped into
func2, and the output of
func2 is piped into
const output = func3(func2(func1(input)));
This is hard to read and unintuitive! While it’d be great if we could use the actual pipeline operator (
Rolling Your Own
The good news is that we can roll our own pretty quickly while we’re waiting. In fact, it can be written as a handy one-liner!
const pipe = (...args) => args.reduce((acc, el) => el(acc)); const output = pipe(input, func1, func2, func3);
…and that’s it! But how does this work? Well, first, we use rest parameters (
...args) to allow for any number of parameters to be passed into our
pipe function and those parameters will be in the array
Next, we use the
Array.reduce method to iterate though the array of
args. As we
reduce, the accumulator becomes the result of passing the previous accumulator to the current element!
A Practical Example
Let’s look at a practical example: converting a blog post title into a slug. We’re going to start our with a string that’s title-cased (e.g.,
"10 Weird Facts About Dogs") and convert it into a slug (e.g.,
"10-weird-facts-about-dogs"). To do this, we’ll wan’t to pipe through a couple functions:
title |> lowercase |> addHyphens
const pipe = (...args) => args.reduce((acc, el) => el(acc)); const title = '10 Weird Facts About Dogs'; const toLowerCase = (str) => str.toLowerCase(); const addHyphens = (str) => str.replace(/\s/g, '-'); const slug = pipe(title, toLowerCase, addHyphens); console.log(slug); // 10-weird-facts-about-dogs
The Actual Pipeline Operator
At the time of writing this post (April 19, 2021), the actual pipeline operator (
|>) is in draft/stage 1 of TC39 consideration. If you’re really itching to use it, There is a Pipeline Proposal Babel Plugin you can experiment with!
Did this post help you?
I'd appreciate your feedback so I can make my blog posts more helpful. Did this post help you learn something or fix an issue you were having?
If you'd like to support this blog by buying me a coffee I'd really appreciate it!
Nick Scialli is a software engineer at the U.S. Digital Service.