The JavaScript Pipeline Operator
yanis.blog
yanis.blog
departments
.flatMap(d => d.employees)
.map(e => e.salary)
.reduce((p, v) => Math.max(p, v), 0)
That said, the pipe operator is nice because it allows similar chaining patterns on subjects that are not arrays, as shown in the proposal’s README: https://github.com/tc39/proposal-pipeline-operator/blob/mast...More useful, IMHO, would be a way to EASILY compose a true pipeline:
const
_pipe = (a, b) => (arg) => b(a(arg)),
pipe = (...ops) => ops.reduce(_pipe)
...but have the behavior work like unix pipes ( a stream ), nodeJS supports this concept at it's most basic level using the pipe() abstraction, although you have to supply methods which handle being pipe'd to, and from... an example: const crypto = require('crypto');
// ...
fs.createReadStream(file)
.pipe(zlib.createGzip())
.pipe(crypto.createCipher('aes192', 'a_secret'))
.pipe(reportProgress)
.pipe(fs.createWriteStream(file + '.zz'))
.on('finish', () => console.log('Done'));
*ripped from: [source](https://medium.freecodecamp.org/node-js-streams-everything-y...)Imagine reading a 100gb json file line-by-line via ajax on the client, and feeding into the pipeline of transformative methods -- iteratively introduce data in one end of the pipe, and gathering the results at the other end, and creating some visualization like a graph or whatever... without ever having to have the entire thing in memory at once...
import { query } from 'itiriri';
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
// Finding first 3 Fibonacci numbers that contain 42
const result = query(fibonacci())
.filter(x => x.toString().indexOf('42') !== -1)
.take(3);
for (const e of result) {
console.log(e);
}
// outputs: 514229, 267914296, 77787420491. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Since ES6 (3 years ago), the only major, mainstream feature that has been added to JS has been async functions, which are awesome, but in that time Python (a language of similar age and global use) has gotten an optional type system, async/await, and _hundreds_ of standard library modules, classes, and functions.
In my opinion, JS badly needs more functions in it's standard library, which should move through the proposal policy quickly. However, common sense standard library functions like flatMap have been in the pipeline for years are still not in the final stage. We may not get flatMap, import(), trimStart, or trimEnd in ES2019, they are all stalled in Stage 3. There's no good arguments not to have these in the standard library, but we still have to wait years.
In addition to that, JS could really use some language features that make it's core paradigms, functional and object oriented, simpler, and have been in other languages for years. The pipeline operator would make functional programming much easier, and decorators would make object oriented programming easier. These are, in my opinion, common sense features since they are so well received in other langauges, but they get stalled out since they are seen as "bloating" the syntax, or making javascript "too opinionated on how to do something". Meanwhile, people are compiling full fledged functional languages (Reason, Elm, Purescript) to Javascript, because Javascript isn't keeping up with them on features. It could, but the TC39 review process is so slow that it's not worth waiting on. For those reasons, in my opinion, we should really be releasing new language features much quicker.
This is one of the arguments for the pipeline operator, as well. Right now browsers are inherently quite afraid of adding things to Object.prototype, Array.prototype, etc, because doing so breaks things. There are too many ancient JS libraries that patch whatever they want into Object.prototype/Array.prototype, such as MooTools, that threaten to break if the prototypes themselves change from what is expected. This is how flatMap() got stuck into "SmooshGate" and the intentionally absurd proposal that it should be named smooshMap(), because if Browsers add Array.prototype.flatMap it does break versions of MooTools still out in the wild.
The pipeline operator is one option (among several proposed options) to move the standard library forward without compromising backward compatibility. Maybe we can't have nice things like `myArray.flatMap()` because it breaks backwards compatibility, but maybe something like `myArray|>flatMap()` is an acceptable compromise.
JS has been adding features at a tremendous rate. Several major features land every year. Adding something like async generators is a huge change that affects large parts of the language.
If the Go, Ruby, or Python guys want to add a feature, they just code up a proposal and add it if the maintainers like it. JS has 4 major implementations and a dozen or so other reasonably popular implementations. Adding a feature in a way that works with all of them (without breaking 25 years worth of applications) is hard.
Reason, Elm, and Purescript are not good comparisons. The features they add (especially the type system) aren't likely to ever be JS features (if they are even possible in the language).
In 2018 the major features we got object rest/spread and asynchronous interation. Rest/spread is a big feature that I forgot to mention, but async iteration is only useful in a few situations, I'd call it a minor feature.
In 2017 we got async/await, and shared memory/atomics. Only a few fringe code bases will use shared/memory/atomics, so I'd call async/await the only major feature.
In 2016 we got 0 major features. The only things in the entire spec (an entire year of language progress) was Array.includes and an exponent operator (). Both of those are very clearly "minor" features.
So in the last 3 years, I'd say we've had 2 or 3 major, mainstream features, that's very far from "several major features every year". Especially 2016 where there were 0 major features.
Atomics is a huge feature (especially in the amount of work required). getOwnPropertyDescriptors is also a big addition.
Async iteration is a very big deal that can potentially affect things like reading files in node. Object spread seems big, but is actually far more simple as it is a syntactic special case of Object.assign(). In contrast, the far reaching repercussions of adding async iteration and the implementation are both large things. Given the level of optimization for JS regex, adding a bunch of new features there is also a big job. Promise finally is also a big update (though combining map and flatmap in promises automatically is the biggest issue with them).
This year, there's integers, working imports, and big class upgrades in the works. The list of major proposals is rapidly shrinking.
Is there another major language adding that many big features in the past three years? Keep in mind that most stage 3 proposals already have at least one implementation already done.
Absolutely. Classes are also a big part of why there's still a lot of bikeshedding for some new features (class properties, decorators, private fields, etc).
Classes are familiar to most developers these days, but they're an absurdly complicated construct. The current implementation in javascript is "maximally minimal", in that the TC39 pushed the minimum they could that was still kind of sortoff useful to get the wheel rolling...but it's still not good enough. They'll need several more updates before they're truly useful. And even when that's all there, they still won't offer much that wasn't already doable, arguably better if less familiar.
At the end of the day, ES6 classes were designed back in the days where OOP was getting big in JavaScript. It took so long to release that by the time they were, the field had changed a lot.
In my opinion, we should be moving forward with features that make functional paradigms easier, such as the pipeline operator, regardless of the fact that JS has object oriented features. There's no reason to stall new features just because different people want different features, at this moment we're pleasing no one with the slow release cycle.
I'd rather that JavaScript continue to add features so that it remains relevant. I like its ubiquity and the the fact that it's both a server and browser language, and would hate to see it get completely railroaded by other language runtimes that can be compiled to WASM.
0 - https://debasishg.blogspot.com/2009/09/thrush-combinator-in-...
Object.prototype.pipeTo = function (functor) {
return functor (this);
};
function inc (input) { return input + 1; }
// this will write out "2" to the console log
new Number (1).pipeTo (inc).pipeTo (console.log);
HTH []+|>
Down from the 6 that jsfuck requires: []+!()Ugh, no, that's a very subjective statement, 64 |> Math.sqrt is not "much more comprehensible" assuming especially for beginners.
It's more convincing (IMO) when chaining calls, eg:
Math.sqrt(Math.ceil(Math.sin(64))) VS. 64 |> Math.sin |> Math.ceil |> Math.sqrt
Why you need operator? Can't it be done with a function?
pipe(64,Math.sqrt)I don't know about you, but I wouldn't want to debug that.
function pipe(...args) { }
pipe(64,sqrt,add,divide,subtract) third(z, second(y, first(x)))
With the pipeline operator (and assuming a language that allows partial application), the order in which things execute matches the order in which you read it: first x |> second y |> third z
The benefits start getting more noticeable when you're talking about stuff like manipulating sets of data. For example: myList
|> filter (x -> x.color == 'red')
|> sortBy (x -> x.count)
|> first
compared to these sorts of pyramids of doom: first(
sortBy(
x -> x.count,
filter(
x -> x.color == 'red',
myList
)
)
)64 |> Math.sqrt |> Math.sin becomes pipe(pipe(64, Math.sqrt), Math.sin)
Assuming pipe was smart and took varags we can make this better.
64 |> Math.sqrt |> Math.sin becomes pipe(64, Math.sqrt, Math.sin)
function pipe(val, ...funcs) {
for (let f of funcs) val = f(val);
}
EDIT: seems like I got ninja'd by an edit :) 64 |> Math.sqrt |> Math.sin
Compiles in the AST to
Math.sin(Math.sqrt(64))
//curries variables away from functions
var realPipe = (a, ...args) => (...initParams) => {
var acc = a(...initParams);
for (var i = 0; i < args.length; ++i) {
acc = args[i](acc)
}
return acc;
}
//if first parameter is a function, curry to delay execution
//if first param is not a function, curry, but call immediately
var pipe = (a, ...args) =>
(typeof a === "function")
? realPipe(a, ...args)
: realPipe(...args)(a)
I'd note that this pipe implementation also bleeds its abstraction. JS has first-class functions, but this will never treat a function as data. You must be aware of how it works so if you are passing a function (for example, a getter function), you must manually curry it afterward.This complication is why most pipe implementations don't actually mess with that data attribute part (they just skip to the realPipe implementation), but since the pipe operator can handle it, I figured I'd try to as well to show the issues.
pipe(64,Math.sqrt,Math.sin)
and pipe(pipe(64, Math.sqrt), Math.sin)
are equivalent.pipe(val, func) => func(val)
then they wouldn't be equivalent but you absolutely could define pipe so they would be.
His lodash and pipeline operator version looked more noisy than the lodash only version.
The more I think about how I use it, the more I realize I'm using it to clean up the leaky abstractions from our backend. If our backend was better, promises would meet my needs fully - get the data, stick it in the views. But no. I have to do all these bullshit transformations and call multiple APIs because apparently Java Spring apps are EXTREMELY DIFFICULT to develop...
Not quite as seamless and it would be nice to have |> but ultimatles introduces a lot of complexity.
The only good reason I could see is if there is a performance benefit a JavaScript JIT could take advantage of by having the |> operator?
The biggest potential benefit is to typing (in Typescript or Flow), which potentially can provide potentially much better or at least much simpler typing and type inferencing with an operator versus many of the alternatives (such as variadic pipe() functions).