K 👓 Feb 04, 2018
The operator is
stage-1 so it won't be included in the standard right away, but you can already use it with the help of babel.
If you come from an object oriented background, you probably used the dot operator quite alot. Many libraries use it to implement small DSLs, often called fluent interfaces, that help you to get things done with good readability.
For example Moment.js
moment().add(2, "days").substract(10, "hours").toString();
An functional alternative is date-fns/fp, but as you can see, the nested function calls make it a bit hard to read.
format("D MMMM YYYY", subHours(10, addDays(2, new Date())));
Now wouldn't it be nice, to have this kind of left-to-right readability for functional code too?
This is where the new piping operator comes in handy, it allows you to make this kind of code more readable.
10 |> f;
date-fns/fp example from above becomes
const add2Days = addDays(2); const sub10Hours = subHours(10); const customFormat = format("D MMMM YYYY"); new Date() |> add2Days |> sub10Hours |> customFormat;
or in short:
new Date() |> addDays(2) |> subHours(10) |> format("D MMMM YYYY");
As you can see, the operator requires a function that only needs one argument. The
date-fns/fp functions return such functions, when only called with one argument.
This also works with asynchronous functions, because they are build on top of promises, which return one result.
"USERID_123" |> await loadUserFromApi // async |> extractUserImageUrl // sync |> await cropUserImage; // async