We are looking for a solution to generate a unique id for messages/signals that are exchanged between clients on the Web, iOS, and Android and later persisted on the backend.
Solution have to be standardized
available on multiple platforms
sortable by created time, indexable by the database
The UUID v1 have these properties except one small thing that sorting and indexing require rearranging of string identifier.
UUID documentation explains that order of time blocks is reversed(starts from milliseconds) (link).
UUID = time-low "-" time-mid "-"
time-high-and-version "-"
clock-seq-and-reserved
clock-seq-low "-" node
time-low = 4hexOctet
time-mid = 2hexOctet
time-high-and-version = 2hexOctet
clock-seq-and-reserved = hexOctet
clock-seq-low = hexOctet
node = 6hexOctet
Because of the UUID representation, we can not sort IDs simply by the string representation of the IDs, and we have to use compare function.
const toSortableUUID = uuidV1 =>
uuidV1.replace(/^(.{8})-(.{4})-(.{4})/, '$3-$2-$1');
const uuidCompare = (uuidV1A, uuidV1B) => {
if (uuidV1A === uuidV1B) {
return 0;
}
const a = toSortableUUID(uuidV1A);
const b = toSortableUUID(uuidV1B);
return a < b ? -1 : 1;
};
const sortedArrayOfUUIDV1 = arrayOfUUIDV1.concat().sort(uuidCompare);
Do you know another standardized approach that will not have this issue?
Would it be correct to use UUID v1 but exchange it between clients rearranged so clients can sort by string representation and do not have to use compare function every time for sorting?
Live test: https://codesandbox.io/s/q5oRxgnp