JavaScript Pipeline Operators
This proposal introduces a new operator
|>
similar to F#, OCaml, Elixir, Elm, Julia, Hack, and LiveScript, as well as UNIX pipes. It’s a backwards-compatible way of streamlining chained function calls in a readable, functional manner, and provides a practical alternative to extending built-in prototypes.
const multiply = a => b => a * b
const divide = a => b => a / b
const add = a => b => a + b
// add(5)(divide(multiply(1)(2))(2))
const result = multiply(1)(2)
|> divide(2)
|> add(5)
The format is similar to chaining with objects but allows similar functionality with immutable, functional programming.
class Obj {
constructor(a) {
this.a = a
this.result = 0
}
multiply(b) {
this.a *= b
return this
}
divide(b) {
this.a /= b
return this
}
add(b) {
this.a += b
return this
}
}
const aObj = new Obj(1)
const result = aObj.multiply(2).divide(2).add(5)
Functional Clarity
The clarity the pipeline operator allows reducing repeating code, and showing the flow more clearly.
html(body(main(div(div(div(h1('hello')))))))
h1('hello')
|> div
|> div
|> div
|> main
|> body
|> html
Warning
⚠ Warning: The details of the pipeline syntax are currently unsettled. There are two competing proposals under consideration.
Those proposals are as follows:
When?
This proposal seems very likely to be added to EMCAScript (ES) standard at some point in the future. The current conflict causes some concern over the time-line but those issues will come to some conclusion.
Now?
Babel currently offers a plugin to offer pipeline operator support.
Note
Currently the smart proposal version has awkward support in different tools with the use of #
. I am currently working around ESLint, Prettier not properly parsing. Depending on your needs you may need to hold off.
ESLint
$ eslint ./physics.js
102:14 error Parsing error: Unexpected character '#'
> 102 | |> multiply(#)(creature.maxspeed)
Prettier
[error] physics.js: SyntaxError: Unexpected character '#' (44:62)
[error] > 44 | velocity: add(state.velocity)(state.acceleration) |> limit(#)(state.maxspeed)
Looking at eslint-plugin-babel
and/or babel-eslint
to add support for these properties.
Smart Pipelines: Topic Reference
The use of
#
as the topic reference is not set in stone.@
,?
,%
, or many other symbols could also be used.