Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active November 11, 2024 08:36
Show Gist options
  • Save fabiolimace/c0c11c5ea013d4ec54cf6b0d43d366c6 to your computer and use it in GitHub Desktop.
Save fabiolimace/c0c11c5ea013d4ec54cf6b0d43d366c6 to your computer and use it in GitHub Desktop.
No Dependency / Do It Yourself / You Know What You Are Doing UUID generator for Javascript
const v4 = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.trunc(Math.random() * 16);
const v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
const v7 = () => {
return 'tttttttt-tttt-7xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.trunc(Math.random() * 16);
const v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).replace(/^[t]{8}-[t]{4}/, function() {
const unixtimestamp = Date.now().toString(16).padStart(12, '0');
return unixtimestamp.slice(0, 8) + '-' + unixtimestamp.slice(8);
});
}
console.log(v4());
console.log(v7());
// Also see: https://gist.github.com/fabiolimace/c725349dd34aedc7b69867dabec59c08
@fabiolimace
Copy link
Author

fabiolimace commented Dec 7, 2023

OUTPUT:

3eab511b-9876-4967-bbd8-e5d56baacdb1
018c469f-f49e-788c-bce0-a41c9eac9c95

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment