|
|
|
|
|
by tinyspacewizard
248 days ago
|
|
Pipes are great where you want to chain several operations together. Piping is very common in statically typed functional langauges, where there are lots of different types in play. Sequences are a common example. So this: xs.map(x => x * 2).filter(x => x > 4).sorted().take(5)
In pipes this might look like: xs |> map(x => x * 2) |> filter(x => x > 4) |> sorted() |> take(5)
In functional languages (of the ML variety), convention is to put each operation on its own line: xs
|> map(x => x * 2)
|> filter(x => x > 4)
|> sorted()
|> take(5)
Note this makes for really nice diffs with the standard Git diff tool!But why is this better? Well, suppose the operation you want is not implemented as a method on `xs`. For a long time JavaScript did not offer `flatMap` on arrays. You'll need to add it somehow, such as on the prototype (nasty) or by wrapping `xs` in another type (overhead, verbose). With the pipe operator, each operation is just a plain-ol function. This: xs |> f
Is syntactic sugar for: f(xs)
This allows us to "extend" `xs` in a manner that can be compiled with zero run-time overhead. |
|
e.g.
So this:
To your example: is a marked improvement to me. Much easier to read the order of operations and which args belong to which call.