5 ms·
Haha, yeah JS integers "can grow". Kind of. And then they bite you in the worst way possible. Especially when combined with cryptography (e.g. nonces). Try thi
by dbrgn 5y ago
Haha, yeah JS integers "can grow". Kind of. And then they bite you in the worst way possible. Especially when combined with cryptography (e.g. nonces).
Try this:
>> const x = 288230376151711740;
>> x == x + 1
true
Or this:
>> 2\*1024
Infinity
JS doesn't even have integers. It only has floats. JS is by far the worst language I know of when it comes to integer support.
If you want a better example of arbitrary precision integers, try Python, for example.
- _moof 5y agoI was working at Twitter when we learned this the hard way. We switched to a separate service for generating tweet IDs (instead of MySQL sequences), which for various distributed systems reasons meant IDs started taking up more bits. And when we stuck those bigger IDs into JSON responses in the API... well, we learned the dumbest lesson possible about the intersection between JSON, JavaScript, and double-precision floating-point. Later that day the "id_str" fields were born.
- dbrgn 5y agoYep, I can totally relate. I found multiple bugs in a MessagePack JS implementation that were related to this issue. I also worked on a project once where unique IDs of objects could get quite large (because they were random u64 integers). Those IDs were serialized and sent to a browser. Sometimes two objects were viewed as "the same" in the browser application because their IDs were truncated by the floating point precision issue.
- johndough 5y agoNeat trick. Math.pow(2, 53) == Math.pow(2, 53) + 1 This is a bit clearer I think. The addition just barely overflows the 53 mantissa bits of the IEEE 754 double precision floating point number. By the way, JS has BigInts these days, which are supported by all major browsers: https://caniuse.com/bigint https://caniuse.com/bigint >> const x = 288230376151711740n; >> x == x + 1n false
- mirekrusin 5y ago2**53 == 2**53+1 ^^ even more clear. That's why Number.isSafeInteger(a) exists. Integers up to +/- 9007199254740991 (Number.MAX_SAFE_INTEGER) are fine.
- thayne 5y agoGP may have been referring to BigInt. Although, C does have an equivalent to that: the GNU MP library (and probably others as well).
- airocker 5y agoI was referring to bigint not js bigint, checking for overflows if optimized could be just 1 instruction.