Idx: Easily access deeply nested nullable fields in JavaScript
facebook.github.io
facebook.github.io
friends = user?.friends?[0]?.friends
It would even work properly with functions: friends = getFriends?()
Which compiles to: friends = typeof getFriends === "function" ? getFriends() : void 0;
`idx` is not quite the existential operator, but it seems cleaner then `_.get`'s string representation of your path.When it gets added to the language, we can codemod away all usage of `idx` to use the question-mark syntax.
If the argument is "because the proposal is immature and could be withdrawn" then the counter argument is that you have basically extended the language already by providing a built in "idx" global much like, say, parseFloat, with the difference that your function does not have any chance of actually being in the spec at any point, unlike the existential operator, thus you're basically masquerading the fact that using idx and the current proposal is the exact same thing just with different syntax.
I made an issue for parser support, and after that we can create a babel plugin though https://github.com/babel/babylon/issues/328.
Until then, we needed to have something that required minimal work (e.g. changes to the parser) that could tie us over until the language had proper support.
Also, we've been using this before the existential operator was formally proposed. (I should've probably got off my lazy butt to publish this sooner, but oh well.)
The plan is indeed to codemod this to the existential operator when it becomes available.
Seeing how verbose and painful it looks, it's also an interesting commentary on macros in JS.
- The path can only be given as a static function literal and there is no function call overhead at runtime because of the bundled babel transform that transforms the code to a bunch of ternary operators.
Also, the transformed code (like all transformed babel) is most likely ugly and more verbose than using lodash's get, no?
However, I wonder why lodash doesn't use a lambda. Parsing that path seems silly. It could just be a try on a lambda https://github.com/lodash/lodash/blob/master/.internal/baseG...
The overall size overhead is what is horrible.
> Also, the transformed code (like all transformed babel) is most likely ugly and more verbose than using lodash's get, no?
Yes, but it also performs at what is probably as-close-to-optimal as possible. The resulting ternaries are extremely easy to work with for even the most basic of JS compilers. Source maps work well - I don't see this as a downside at all.