Hacker News new | ask | show | jobs
by ridiculous_fish 3273 days ago
TypeScript addresses many of JavaScript's type-related issues but retains other JavaScript insanity: bizarre array semantics, Unicode ignorance, no integer arithmetic, regex facepalms, Math weirdness, etc.
1 comments

What do you mean by bizarre array semantics? Genuinely curious.
Oh man, how much time do you have...

The root of the wtf is how Arrays play double-duty as both indexed and associative. The ES spec says that if you modify a property of an array object, the implementation must check if the (necessarily String) key changes after being round-tripped through a UInt32 conversion. If not, the key is a special array index that bumps the length; otherwise the length is unaffected.

    var arr1 = []; arr1[2147483648]=1; // arr1.length == 0
    var arr2 = []; arr2[2147483647]=1; // arr2.length == 2147483648
    var arr3 = []; arr3[-1]=1; // arr3.length == 0
Of course strings participate in this nonsense:

    var arr = []; arr["12345"] = 1; // arr.length == 123456
This is JavaScript so naturally .length is settable:

    var arr = []; arr.length = 3; // works!
But implementations are still required to distinguish between keys that are undefined and keys that outright don't exist:

   var arr = []; arr.length = 3;
   arr[0] = arr[2] = undefined;
   for (key in arr) print(key); // 0, 2
And of course you can set whatever random associative array property you like:

   var arr = []; arr[1] = true;
   arr[3.5] = false; // "works", .length is still 2
The intent is that array implementations may use efficient unboxed contiguous storage, but the spec requires that arrays may be sparse so it's still necessary to track which keys are actually set even if values are undefined.

Want to iterate an array's keys? There's no requirement that array indexes start at 0, and you may encounter random other keys from the array prototype.

TypedArrays are more limited/sane, thankfully.

Every time I see something like this, I stop and consider just how saner Lua is, even though in many ways it adopted similar approaches (e.g. associative arrays doubling as regular ones).
>32bit number indices not affecting length is crazy - I didn't know about that (I don't think I've knowingly dealt with an array that big).

TypeScript thankfully prevents all of these errors except for the one I mentioned.

Do you work on the spec or a JS implementation? That's some pretty impressive knowledge.

I have not implemented Array, but I know the poor soul who did!