Skip to content

Instantly share code, notes, and snippets.

@juanluisja1
Forked from ifandelse/uuid.js
Created November 1, 2023 22:07
Show Gist options
  • Save juanluisja1/4aa4e653c013766dc0d4122e26bbcbf8 to your computer and use it in GitHub Desktop.
Save juanluisja1/4aa4e653c013766dc0d4122e26bbcbf8 to your computer and use it in GitHub Desktop.
Looking for "Good Enough" client-side UUID generator
/*
I cannot claim this - it was recommended by a friend as a 'good enough' unique id generator
for local client side scenarios in the browser. The use case I'm looking to address has to
do with cross-frame messaging, where each point of origin needs a unique id (to be used as an
"origin" or correlation identifier). Therefore - the IDs do not need to be unique on a large
scale (e.g. - across a vast network of connected clients), but only in the browser, locally,
for the life of the session. Question is: is this good enough?
*/
function createUUID() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
return s.join("");
}
@juanluisja1
Copy link
Author

UUID strong enough for client applications, not for scale.

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