Last active
February 10, 2024 15:47
-
-
Save benhatsor/b40d83acafa7bae1ed70eb76a2ed51a6 to your computer and use it in GitHub Desktop.
Generate a unique ID based on the current time. Note: If you need a truly unique ID, use something like the JS Crypto API instead.
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
// Both numbers and letters | |
function mixedID() { | |
var now = new Date(); | |
timestamp = now.getFullYear().toString(); | |
timestamp += (now.getMonth < 9 ? '0' : '') + now.getMonth().toString(); | |
timestamp += ((now.getDate < 10) ? '0' : '') + now.getDate().toString(); | |
timestamp += now.getHours().toString(); | |
timestamp += now.getMinutes().toString(); | |
timestamp += now.getSeconds().toString(); | |
timestamp += now.getMilliseconds().toString(); | |
id = 'a'; | |
for (var i = 0; i < timestamp.length; i++) { | |
id = id + String.fromCharCode(97 + Number(timestamp[i])) + (Number(timestamp[i]) + 5); | |
} | |
return id | |
} | |
// Letters | |
function baseID() { | |
var now = new Date(); | |
timestamp = now.getFullYear().toString(); | |
timestamp += (now.getMonth < 9 ? '0' : '') + now.getMonth().toString(); | |
timestamp += ((now.getDate < 10) ? '0' : '') + now.getDate().toString(); | |
timestamp += now.getHours().toString(); | |
timestamp += now.getMinutes().toString(); | |
timestamp += now.getSeconds().toString(); | |
timestamp += now.getMilliseconds().toString(); | |
id = ''; | |
for (var i = 0; i < timestamp.length; i++) { | |
id = id + String.fromCharCode(97 + Number(timestamp[i])); | |
} | |
return id | |
} | |
// Numbers | |
function numID() { | |
var now = new Date(); | |
id = now.getFullYear().toString(); | |
id += (now.getMonth < 9 ? '0' : '') + now.getMonth().toString(); | |
id += ((now.getDate < 10) ? '0' : '') + now.getDate().toString(); | |
id += now.getHours().toString(); | |
id += now.getMinutes().toString(); | |
id += now.getSeconds().toString(); | |
id += now.getMilliseconds().toString(); | |
return Number(id) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Neat
What if two generations happen on the same ms? -> same id?
Differences with Ulid? KSUID?
Any boundary limits?