Piping JavaScript

K - Feb 4 '18 - - Dev Community

Cover image by arbyreed on Flickr.

JavaScript is getting more and more functional programming features, an exiting one is the new pipeline operator.

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.

Why

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();
Enter fullscreen mode Exit fullscreen mode

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())));
Enter fullscreen mode Exit fullscreen mode

Now wouldn't it be nice, to have this kind of left-to-right readability for functional code too?

What

This is where the new piping operator comes in handy, it allows you to make this kind of code more readable.

f(10);
Enter fullscreen mode Exit fullscreen mode

becomes

10 |> f;
Enter fullscreen mode Exit fullscreen mode

So the 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;
Enter fullscreen mode Exit fullscreen mode

or in short:

new Date()
|> addDays(2)
|> subHours(10)
|> format("D MMMM YYYY");
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Conclusion

Again, JavaScript takes a step into the FP direction and build on top of the additions it already had. Especially server-side data-transformation code will profit from code written this way.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player