Skip to content

Instantly share code, notes, and snippets.

@jpalala
Created June 21, 2024 03:08
Show Gist options
  • Save jpalala/78e8dc82a0cc4cb79030fefc595b3f7a to your computer and use it in GitHub Desktop.
Save jpalala/78e8dc82a0cc4cb79030fefc595b3f7a to your computer and use it in GitHub Desktop.
uniqid2
// from my thinking this is much faster than uuuid as long as you do not same microsecond requests
function uniqId2() {
const hrTime = process.hrtime.bigint();
const microTime = hrTime / BigInt(1000);
const randomComponent = Math.floor(Math.random() * 16).toString(16); // generates a random hexadecimal digit
return microTime.toString(16) + randomComponent;
}
function idToTimestamp(id) {
const idWithoutRandomComponent = id.slice(0, -1); // remove the random component
const microTime = BigInt('0x' + idWithoutRandomComponent); // convert from hexadecimal to BigInt
const hrTime = microTime * BigInt(1000); // convert from microseconds to nanoseconds
return Number(hrTime) / 1e9; // convert from nanoseconds to seconds
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment