JS things I didn’t know existed
air.ghost.io
air.ghost.io
The only exception I made was a quick pre-screen (to be completed in their own time with no pressure) in which candidates received 3 or 4 code snippets, and were asked a couple of questions about them which they wrote answers out in plain English explaining their thought process, in however much detail they wanted. (Thinks like a piece of code where "this" would break because of context, or a cross domain request that would fail and some ways to approach solving).
Even then, that was used as a ways to say "ok, this candidate clearly has good understanding, we'll not hang about too long during the interview process on that topic".
If they didn't mention what we thought the answer was, it didn't count against them at all, it just gave us an area to explore in the interview. (Because who's to say our pre-screen question wasn't the problem?)
Same in your situation. Why didn't they try it out before making a judgement?
Wait does JS really have curly braces? Not sure now, I haven't read the spec from cover to cover three times; better go try it.
Okay, super exaggerated example (but I like those; they get the point across).
Also, empirical approaches can appear to confirm intuitions that are wrong; like printf("%d %d\n", i++, i++) producing the wrongly expected answer.
I view it as test. When an interviewee or a new guy at work tells me something that I don't know or think is wrong I always give him the benefit of the doubt and verify it together with him. If he is right I know we have somebody who brings something to the table. If he is wrong that's clearly a negative that counts against him. If that happens a few times I will stop listening to that person.
Hell, simply writing a program to accomplish some specific goal is an empirical exercise that further enriches existing understanding.
Of course, as you note, empirical guess-and-check knowledge with no theoretical understanding is also a problem.
This mirrors my interviewing experience. People read so much into every answer during these stupid whiteboard interviews. I'm guessing that the candidate didn't get the position because they didn't seem to know JS well enough?
And this is why if people mention a whiteboard as part of the interview process, I don't bother. I've seen similar arrogance related issues in regards to security/crypto questions. The ability to demonstrate the code actually runs and/or is actually broken from a security perspective is an invaluable part of the process.
I did get the job.
I would caution people against using some of these "features" though as writing clever code that leverages obscure techniques is NOT good for readability and maintainability.
The person who has to maintain your code will probably be able to more easily grok some boring if else statements than some weird ternary thing that leverages the comma operator.
Just because you can doesn't mean you should.
Compare
2 |> square |> increment |> square
and pipe(2, square, increment, square)
where `pipe` is defined as const pipe = (...args) => args.reduce((prev, curr) => curr(prev));
So given that what would be a strong argument for introducing the operator to JavaScript? function tee(arg) {
console.log(arg);
return arg;
}
2 |> square |> tee |> increment |> square; const tee = arg => console.log(arg), arg; const result1 = square(2);
const result2 = increment(result1);
const result3 = square(result2);
With the above, I can add in a breakpoint and inspect what's going on at each stage with access to other debugging tools. Log statements don't seem nearly as good as this. The above is nice as well in that you can give intuitive names to the intermediate results.BTW A nice feature of a code editor would be if you could magically switch back and forth between code with intermediate named variables and pipelined version of the same code, e.g. by selecting the code and invoking an option.
const pipe_debug = (...args) => args.reduce((prev, curr) => {
console.log('pipe debug; curr:', curr, ', prev:', prev)
return curr(prev)
})
and when you want to see intermediate results of a `pipe` call, you append `_debug` to the name.As for the second thing, I'd agree, but instead of introducing an operator, we could make the helper a built-in feature.
initialValue
|> doSomething
|> doSomethingElse
|> reportResults
In which case I think it's extremely readable compared to the alternatives. pipe(initialValue
, doSomething
, doSomethingElse
, reportResults
)
Is it really so much more readable with the operator? square(increment(square(2)))
and get the same result, right?"The point is readability. It's UX for the programmer, reducing cognitive load in understanding what's going on. Pipes are fantastic in the terminal and have never been replaced there because they are very simple glue piecing together the complex bits with a simple-to-understand model.
If we can have that in JS, I'd be quite pleased even if there are other ways to do the same thing.
The advantage of the operator and the `pipe` helper over regular function composition is that you can emphasize the flow of data through a pipeline of functions.
The only advantage in readability I see here is that the operator is hard to mistake for anything else, it sticks out of the code, more than a seemingly regular function call. But this is not an advantage that justifies introducing the operator.
Other than that, UX and cognitive load is the same.
Pipes can indeed be fantastic! ;)
*
Apropos composition: why not add a composition operator while we're at it? Or we could define something like:
const compose = (...args) => pipe(...args.reverse())
and then compose(square, increment, square, 2)
;)For me there is also something more ineffable that's important here. A question of whether adding a new built-in operator fits within the general philosophy or some sort of "look & feel" of the language, or whatever. I think JavaScript seems to be quite conservative, when it comes to bringing in new operators. Perhaps that's a good thing. Maybe not. But so far, I remain unconvinced.
const pow = x => y => Math.pow(x, y);
pipe(2, pow(5), square);
compared to just: 2 |> Math.pow(5) |> square 2 |> Math.pow(5) |> square
from? This would mean the same thing as: Math.pow(5, 2) |> square
right? This seems like a pretty hairy thing to implement into the language. Also I don't think this syntax is very clear.A more concise way of doing this with `pipe` would be:
pipe(2, $ => Math.pow(5, $), square)
Compared to the operator: 2 |> $ => Math.pow(5, $) |> square
So no disadvantage at all.[0] https://github.com/tc39/proposal-pipeline-operator#user-cont...
I really like the partial application example from your source:
let newScore = person.score
|> double
|> add(7, ?)
|> boundScore(0, 100, ?);
Partial application is a separate stage 1 proposal but together with the pipe operator I really prefer this: let x = 2
|> Math.pow(5, ?)
|> square
to this: let x = pipe(2, $ => Math.pow(5, $), square) let x = pipe(2
, Math.pow(5, ?)
, square
)
;)But here's a try ;)
I take it that the meaning behind the words you used is:
clean:
no need for `pipe(` prefix and `)` postfix
expressive: can convey a pipeline in a distinctive and unique way
(with a special operator as opposed to regular function)
Let me use the same words, but with different meaning, to say "the pipe function is much cleaner and expressive IMO".The meaning would be:
clean:
looks (is) the same as regular function application,
no need for dirtying the syntax up with
a special operator
need to only press one extra key per operand/argument
(,) as opposed to 3 (shift+|,>) ;)
expressive: can convey a pipeline just as well as the operator;
it's a regular function, so it's first class,
unlike the operator
it's variadic, so you can combine it with
spread operator syntax like:
pipe(data, ...pipeline1, ...pipeline2)
// where pipeline1 and pipeline2
// are arrays of functions //implementation of your pipe in terms of the (potential) pipe operator
Function.pipe = (fn, ...args) => {
//let's use a pseudo Duff's device
switch (args.length) {
case 0: return fn;
case 1: return fn |> args[0];
case 2: return fn |> args[0] |> args[1];
case 3: return fn |> args[0] |> args[1] |> args[2];
case 4: return fn |> args[0] |> args[1] |> args[2] |> args[3];
case 5: return fn |> args[0] |> args[1] |> args[2] |> args[3] |> args[4];
case 6: return fn |> args[0] |> args[1] |> args[2] |> args[3] |> args[4] |> args[5];
case 7: return fn |> args[0] |> args[1] |> args[2] |> args[3] |> args[4] |> args[5] |> args[6];
case 8: return fn |> args[0] |> args[1] |> args[2] |> args[3] |> args[4] |> args[5] |> args[6] |> args[7];
default:
var mod = args.length >> 3; //div by 8
var rem = -8 * mod + args.length; //mult add
fn = Function.pipe(fn, ...args.slice(0, rem));
while (rem < args.length) {
fn = fn |> args[rem++] |> args[rem++] |> args[rem++] |> args[rem++] |> args[rem++] |> args[rem++] |> args[rem++] |> args[rem++];
}
return fn;
}
};
It's a little off topic, but I'd love to see the addition of well-known symbols for all the operators to allow custom overloading. Lua does operator overloading with metatables. No reason JS can't too. At that point, pipe, compose, and even spaceship become much more useful. var x = {
foo: [1,2,3],
[Symbol.add](rightHandSide) {//Binary
return this.foo.concat(rightHandSide);
},
[Symbol.incr]() {//Unary
this.foo = this.foo.map(x => x += 1);
return this.foo;
}
}
//default to standard operator if
//if left side is primitive or if
//left side has no matching Symbol
x + 3; //same as x[Symbol.add](3)
[0].concat(x++); //=> [0,1,2,3]
//same as [0].concat(x); x[Symbol.incr]();
[0, 1].concat(++x); //=> [0, 1, 2, 3, 4]
//same as x[Symbol.incr](); [0, 1].concat(x);> I'd love to see the addition of well-known symbols for all the operators to allow custom overloading.
Sure, if we had support for first-class overloadable operators then a proposal to add a standard operator like `|>` would make sense. But we don't, so a better one would be to add `Function.pipe` (simple, fits into the language better) or allow operator overloading, etc. (also may be reasonable, but it's a major change in the language).
> 2 |> square |> increment |> square
So, looks like any sufficiently complex language nowadays carries a badly self-compatible, inextensible, limited set of popular Haskell libraries.
And also Lisp's seq. Other Lisp features are left for implementation on a Lisp interpreter once your application gets large.
Don't know what you mean by that.
> But they can (and had) added support for the |> operator.
Doesn't seem like they did: https://github.com/Microsoft/TypeScript/issues/17718 https://github.com/facebook/flow/issues/5443
Also yeah javascript has labels but using them is usually a bad idea. While they may seem useful they can be harder to reason about in all but the simplest code. You're almost always better off restructuring your code instead of using labels.
If the handler goes missing or fails, this construct will prevent the link from doing what it usually would.
But using a button is better in such cases...
Back then, you'd use it with the `href` attribute to prevent the link from going anywhere (it would return `undefined`), then call a function with the `onclick` attribute.
E.g.
<a href="javascript:void(0)" onclick="clickHandler()">Click me</a> <a href="javascript:void(0)" onclick="dostuff()">Click me</a>
href="javascript:void(0)" basically tells the browser to do nothing when a link is clicked. It's like returning false from an event listener.onclick="dostuff()" will then listen for clicks and call the `dostuff` function to update the page or load a new one.
Nowadays it's considered bad practice and to be honest it wasn't exactly good practice in those days but it was very commonly used.
On the other hand, if the event loop's job also includes rendering the game's UI, then leaving it by any means will freeze the display until it's restarted. That's probably bad too, although I suppose in theory it could be turned into a game mechanic. Absent that, this technique might make more sense in a case where you're running the exitable loop in question on a secondary thread (i.e. a worker), and doing things with it which can be safely interrupted - maybe changing levels or something, where the player isn't expecting to do anything during a UI transition, and you need to await the arrival of some resources over the network and then set up the game state before restarting the event loop to resume normal play? I don't know, that's a bit contrived and probably flawed in a critical way, but I think it makes the same basic sense as offloading heavy and necessarily synchronous work to a worker thread does in general.
Granted, it's a fair bit of work to set up in the first place - more in deciding what to allow and what not to; eslint itself is very friendly in my experience. And someone who just flat-out refuses to play along might not be a problem this tool can solve - although perhaps you can all reach a modus vivendi around an acceptable level of novelty somewhere short of the bleeding edge. (We use TC39 level 3. You might prefer something more conservative, such as level 4, or some version of ECMA-262 proper.) But it's worth a look, I think, as a tool that might reduce the headaches you seem frequently to be stuck with. I hope you find it useful!
It’s not if it meets your second and third conditions. I don’t think the comma operator or `void` qualifies as things that can "significantly simplifies an implementation". Even the labels thing looks like a great opportunity for spaghetti code.
As a counter argument... switch this reasoning from syntax to algorithm, if an algorithm is too complex for most people to understand at first glance, do you throw it away in favour of a simple but inferior choice for the problem at hand?
This is not the same problem. Syntax is only a way of writing the same code in a different way.
Many of them opinionated and arbitrary, but it's easy to draw the line based on your own experience and unwittingly cast out people with more or less knowledge than yourself as being more obscure or more common.
> the threshold you pick is completely arbitrary
The threshold you pick is the result of a cost/benefit analysis weighing ease of understanding against whatever the benefit of that feature is.
In the case of the algorithm, I'd want to know how much faster the complex one runs or how much better its results are. If the answer is, "a fraction of a percent" in both cases, I probably don't care, unless maybe I'm Google and handling enough volume that a fraction of a percent matters.
That comma operator is pretty odd; someone could easily be surprised by that behavior. Labeled breaks and additional arguments to setTimeout, though, do exactly what they look like. You might be surprised that the code works, but you wouldn't be so surprised at what it does.
I understand what you mean, but most of the described features has been in the language for ages, some of them more than 20 years.
I think the reason why so many aren't aware of the features, is because they learn the language by looking at code written by others or from simplified tutorials, and never look at the formal specification.
I remember how I struggled back in the late 90's to find good information, and how I read the ECMA-262 specification when I found it. Whenever a new specification is released I download it and read though it to see all new features, and also refresh my memory about the old.
const x = (1, 2, 3) // 3
x === (1, 2, 3)
Javascript's tuples have some great compression!It doesn’t really make sense to put it in the article, it is completely unrelated to the other arcane and unsafe features that precede it.
The latest comments from the devs on the bug in chrome is just depressing.
I wouldn't be surprised if the syntax was even older. And the functionality has likely been used in some academic language from decades ago. It's just reverse function composition after all.
F# can’t precedes OCaml because it’s based on it. OCaml was first released in 1996 while F# appeared only in 2002.
First implemented in Unix V3 1973, acording to wikipedia.
1994: Isabelle/ML (part of Isabelle proof assistant tooling) (https://blogs.msdn.microsoft.com/dsyme/2011/05/17/archeologi...)
2005 and earlier: F#
2012: Elm
2013: Elixir (https://github.com/elixir-lang/elixir/pull/751)
2013: OCaml (https://ocaml.org/releases/4.01.0.html)
f |> g = g . f