Created
June 21, 2024 03:08
-
-
Save jpalala/78e8dc82a0cc4cb79030fefc595b3f7a to your computer and use it in GitHub Desktop.
uniqid2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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