TIL about the proposed pipe operator
POSTED ON:
TAGS: javascript functional-programming
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: javascript