80 points · by bpierre · 5y ago · 144 comments
V8 + dynamic language + better math support = perfect environment for many applications out there
You might miss out on some SIMD operations, but you'd be able to do 90% of what you'd want with scientific calcs. (admittedly, it'd be nice if this were part of the language).
I’ve only worked on probability applications at a surface level for a tiny bit and never really needed it, but I kept wondering whether there were such a numeric types, and if not, what people did if they needed it.
Log odds ratios are also good representations that have this kind of accuracy between zero and one. They're good when you need them. (e.g. 100:1 odds are log(100/1) and 1:100 odds are log(1/100))
Is it just a matter of there being a "blessed" implementation for folks to standardize around?
Support for this I believe is "low level enough" to ve implemented natively, it's not something like protobuf.
const at = (arr, i) => i >= 0 ? arr[i] : arr[arr.length + i];
Why does the core language need to be extended to incorporate this?I had the exact same thoughts when `.includes()` was proposed to be added to the spec - it's just `.indexOf() !== -1`! - but time has proven me wrong, and I suspect it will prove us wrong about `at` as well.
I've written an `.indexOf() !== -1` check hundreds if not thousands of times, and I've gotten the conditional wrong enough times to actually need to revert a change in prod.
I have similar thoughts about .at(). Taking an element from the end of the array is ever-so-slightly error prone. Sure, you won't make a mistake this time, or the next time, but write it a hundred times, or a thousand, and I bet a bug will slip in. It's darn near impossible to get `.at(-1)` wrong, however.
Also: `[1, NaN, "hi"].indexOf(NaN)` is -1 but `.includes(NaN)` returns true as expected.
Brutal.
You need to use a transpiler (like Typescript), but at this point, there no reason to implement that in the language, a transpiler can implement the feature by simply adding the method to the prototype of the object, like this:
Array.prototype.at = function (i) { return i < 0 ? this[this.length + i] : this[i] }Plus you're probably missing a few dozen edge cases and optimizations that the native version would incorporate.
We wouldn't have been in node_modules dependency hell if they incorporated a few more things into the standard library or language.
We shouldn't write stuff in native code for performance... We should write the compiler to detect these and output optimized code.
- frameworks like react or express and extensions for the same
- meaningful libraries like axios, ramda, date-fns or qs
- transpiler/bundler enhancements like webpack loaders or babel presets
I would prefer that the JS committee focused on bringing meaningful new capabilities to node and the browser that are currently lacking, like they did with the various HTML5 libraries, fetch(), ES classes and so on, rather than providing tiny functions that aren't even providing new functionality (array indexing is easy and idiomatic in JS). If there was no opportunity cost then sure, add tiny pointless builtin functions all day long.
Those tiny little libs providing tiny little functions are likely not direct dependencies of your application, rather dependencies of a subdependency of a subdependency of a subdependency of your preferred "meaningful" library.
FWIW, I consider `at` to be similar to some of the things you consider "new capabilities". `fetch` vs `XMLHttpRequest` is fairly analogous to `at` vs `arr[i]`, and similar arguments can be made about ES6 classes over prototypal classes, etc.
const leftpad = (str, len, char = ' ') => str.length >= len ? str : (char.repeat(len - str.length) + str);
Anybody who installs a dependency instead of writing a one line function is just leaving themselves exposed for no real benefit.Providing the at function outside of the prototype chain like I did above will not incur the cost you mentioned, even in the unlikely case that such calls are the bottleneck of your application.
Plus, if array lookup calls are your bottleneck then you probably need a different data structure.
Just look at your at() function, I already spotted a bug, if a numeric string is passed: `([].length + '-1') === '0-1'`
Auditing the entire dependency tree of every library you choose is extremely arduous without proper tooling, and the tooling here has never been good (and even the more recently available better tooling is CVE-focused so won't highlight tells like package size/maintenance status/whatever other heuristics you might devise as a proxy for quality).
const leftpad = (str, len, char = ' ') => str.padStart(len, char);Unfortunately, I couldn't find any links to articles written at the time about this, but they definitely did consider "use" options or script type="es2021" kinds of options.
I absolutely agree that some metadata at the top of a module enabling behavior like this would be ideal.
From a spec perspective, ES6 modules were a good milestone to "flip the switch" over to strict mode by default, but even with that being a fairly successful strategy (IMHO), it still left some nasty corner cases around the language (namely, there are now two distinct top level grammars, which led to the whole .mjs bikeshedding rabbit hole)
We need more special contextual comments to change a file or scope to behave better so we can move forward and scrape away all the bad legacy of JS.
But perhaps we just don't know enough, and they will add the `at`, and at some point actually do bind `arr[index]` to use the implementation of that function?
Instead, adding .at() allows having the new feature now, and in a way that's possible to polyfill for backwards compatibility.
In the face of disasters like Python 2->3 and Apple M1 macs no longer being able to play Starcraft Remastered, the web is an aspirational beacon.
Let’s keep it going.
An organization can go through and update its C++, because ultimately they're distributing binaries (or doing everything internally and not distributing anything at all).
Web "pages" aren't called that for no good reason. If in 2005 you bought a novel, or some punk writer–artist's printed pamphlet, and now you can't read it because in the meantime some engineers changed a spec somewhere, then that would be a failure, not just in the small, but on a societal level. Just rev the language is something that people who spend 40+ hours in an IDE or programmer's text editor think up when they're used to dealing in SDKs and perpetually changing interdependencies and fixing them and getting paid handsomely for it. But that's not what the Web is. The Web is the infrastructure for handling humanity's publishing needs indefinitely.
To rely upon another observation:
"[This] is software design on the scale of decades: every detail is intended to promote software longevity and independent evolution. Many of the constraints are directly opposed to short-term efficiency. Unfortunately, people are fairly good at short-term design, and usually awful at long-term design. Most don’t think they need to design past the current release."
https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypert...
I dislike the abuse of this word. Lacking some shorthand notation doesn't make the language "broken".
It reminds me of handling support tickets where clients say "X needs to be urgently fixed" even though X has never been possible. (Should it? Often yes, but it doesn't mean it's broken.)
array[-1] = “foo”
This already works in JS but doesn’t do what you expect and just assigns the property. array["foo"] = "bar"
is valid javascript. array["at"] = "lunchtime";
Is also valid javascript... And will break functionality in this proposal!So [0, 1, 2, 3].at(-2) === 2
I don't like that very much.
Mind you, I don't like the idea of using [0,1,2,3].at(-0) either...
Or, if it’s more intuitive, you can think of the array index as an unsigned integer where the max is equal to the length of the array. If you try to assign -1 to a uint8, the result will be 255 — the highest possible value (the last index).
[1, 2, 3, 4].at(0) === 1
[1, 2, 3, 4].at(1) === 2
[1, 2, 3, 4].at(-1) === 4
findIndex’s behavior is unchanged.
See: https://tc39.es/ecma262/multipage/notational-conventions.htm...
Quite disappointed so, my parent comment doesn't stand too
I've lost count on how many times I've wrote this function manually.
That works in this case, but eta-reduction is not generally safe in Javascript due to the variadic nature of many functions, so I wouldn't recommend it in production code. For example `indices.forEach(console.log)` does not work as one would expect.
> Uncaught TypeError: Cannot convert undefined or null to object
because `myObjectArr.at` doesn't bind `this` to `myObjectArr`. When the internals of `map` call the `at` function, `this` is just `undefined` instead of the original array and it'll throw.
Luckily Array.prototype.map takes a second argument just for this purpose
indices.map(myObjectArr.at, myObjectArr)There should really be a whole new standard library made from ground up without `this`, mutability and all the other legacy stuff.
It's not a big thing of course with such a simple example, but just try to program without defining a single function and you'll see how tiresome it soon begins to write everything out manually.
const arr = [];
arr[-1] = 'Hello world';
console.log(arr[-1]);
// Hello world
Instead of using the negative index, it stringifies the "-1" and uses it as the key of an object both when writing and reading. Thus, arr.length still remains 0But I guess the intersect between C++/JS developers is too small to care
However I think there is a better way to support that - make `throw` an expression rather than a statement. Then you can do
a[10] ?? throw new Error()
which currently doesn't work.