Today I Learned - Rocky Kev

TIL about the proposed pipe operator

POSTED ON:

TAGS:

In functional programming, you chain functions to provide a result.

For example:

const money = 10;

const total = addFiveDollars(addTwoDollars(removeOneDollar(money)))

Valid.

And also horribly unreadable.

In other languages, there's a pipe operator to make functional programming more readable.

It looks like this:

output = input -> func1 -> func2 -> func3

There are two competing proposals for the Pipe Operator in javascript.

There originally were two competing proposals for a pipe operator, inspired by other programming languages:

F# by Microsoft is a functional programming language whose core is based on OCaml. This pipe operator works together well with curried functions (I’ll explain what that is soon).

Hack by Facebook is – roughly – a statically typed version of PHP. This pipe operator focuses on language features other than curried functions. It includes syntactic support for partial application.

The latter proposal won. However, if you prefer the F# pipe, there is good news: Its benefits may be added to the Hack pipe at a later time (details are explained later).

The future can look like this:

const money = 10;

// old ugly format
// remove $1, add $2, add $5

const total = addFiveDollars(addTwoDollars(removeOneDollar(money)))


// newer attractive format
// remove $1, add $2, add $5

const total = money |> removeOneDollar |> addTwoDollars |> addFiveDollars

A pipe operator for JavaScript: introduction and use cases


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.