4 ms·
Quite incidentally, this is fixed with the addition of one character: const at = (arr, i) => i >= 0 ? arr[i] : arr[arr.length + +i];
by chrismorgan 5y ago
Quite incidentally, this is fixed with the addition of one character:
const at = (arr, i) => i >= 0 ? arr[i] : arr[arr.length + +i];
- zodiakzz 5y agoNit: it throws if you wanna use a negative bigint as `i` hehehe :( let i = -1n; let test = +i; > Uncaught TypeError: can't convert BigInt to number See this is where standard libraries shine, they consider all the pieces of the puzzle. There's no good reason to disallow bigints here. P.S: Unary plus operator is neat but this TypeError with BigInt is why I am starting to prefer the more verbose `Number(i)`.
- chrismorgan 5y agoHmm, I had completely forgotten about that distinction. I also can’t find it in the spec <https://tc39.es/ecma262/ https://tc39.es/ecma262/>, which says that Number “performs a type conversion when called as a function rather than as a constructor.” <https://tc39.es/ecma262/#sec-number-constructor https://tc39.es/ecma262/#sec-number-constructor>. What this means isn’t spelled out, which seems poor. I would have thought it meant ToNumber <https://tc39.es/ecma262/#sec-tonumber https://tc39.es/ecma262/#sec-tonumber>, but that would throw an exception on BigInt (like unary plus does, <https://tc39.es/ecma262/#sec-unary-plus-operator https://tc39.es/ecma262/#sec-unary-plus-operator>). So now I’m guessing it means ToPrimitive <https://tc39.es/ecma262/#sec-toprimitive https://tc39.es/ecma262/#sec-toprimitive> with preferredType number, which seems to match. This being the case, I believe BigInt is the sole difference between +x and Number(x).