The Twitter API returns IDs that are 64 bit integers, such as 276403573577891842. I want to see if one Tweet is newer than another by comparing their ID’s.
Is there a clever way to compare two 64 bit integers to see which is greater in JavaScript which only supports 32 bit integers?
Assuming the API is returning strings which are then parsed into ints, there are two ways to do this – a split way and a pad way;
Split.
The idea here is to split the data into a size the environment can handle. Largest 32-bit number is
0xFFFFFFFFor4294967295. Now4294967295..toString().length === 10. So all dec with str length <= 9 should be 32-bit safe.Pad.
The idea this time is to do a string comparison, but to do that we must first make sure the (string) numbers have the same length; i.e. pad them with 0s. This time
'18446744073709551615'.length === 20soNow you can use
a === b, a < b, a > bso normal (except you’re using strings and not int).