In JavaScript, the pipeline operator has progressed through the TC39 process, starting as a topic of discussion for many years, moving to draft stage 1, and currently being in progress on stage 2.
The pipeline operator is a proposed feature for JavaScript that allows for chaining function calls together in a more readable and concise way. It's an operator that takes the output of one function and passes it as the input to the next function in the chain. This can make code more readable and expressive, by allowing developers to create a "pipeline" of operations on data.
The operator is represented by the |>
symbol and is placed between the output of one function and the input of the next.
Use cases examples
Let's start with a simple example. Let's say we have a simple function that takes a number and doubles it:
javascript
const double = (num) => num * 2;
Now, let's say we have another function that takes a number and adds 1 to it:
javascript
const addOne = (num) => num + 1;
Normally, we would call these functions like this:
javascript
const doubled = double(5);
const result = addOne(doubled);
return result;
Or even better with a one line solution:
javascript
const result = addOne(double(5));
console.log(result); // 11
But what if the operations are more? The code could be not so good to read...
With the pipeline operator, we can chain these function calls together in a more readable way:
javascript
const result = 5 |> double |> addOne;
console.log(result); // 11
As you can see, the pipeline operator makes it clear that the output of the double
function is being passed as the input to the addOne
function. This can make code more readable, especially when working with complex data pipelines.
Another example is when we want to filter an array of objects and get only the ones that have a specific property.
javascript
const filterByProp = (prop) => (arr) => arr.filter((x) => x.hasOwnProperty(prop));
We can use the pipeline operator to chain our filterByProp
function with the map
function to get only the specific property of the objects that pass the filter.
javascript
const result = arr |> filterByProp('name') |> arr.map((x) => x.name);
These are just simple examples, but as you can see, the pipeline operator allows developers to create a "pipeline" of operations on data, making it clear what is happening to the data at each step in the process.
It's important to keep in mind that this feature is not officially part of the JavaScript language yet, but it's available through some transpiler plugins like babel-plugin-proposal-pipeline-operator.
So next time you're working on a complex data pipeline, consider using the pipeline operator to improve your code!