Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created February 17, 2022 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topherPedersen/5a7f7a4873cef3c6a3c2155719d876b6 to your computer and use it in GitHub Desktop.
Save topherPedersen/5a7f7a4873cef3c6a3c2155719d876b6 to your computer and use it in GitHub Desktop.
Generate UUID in JavaScript
/*
UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to RFC 4122, are identifiers designed to provide certain uniqueness guarantees.
While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see @broofa's answer, below) there are several common pitfalls:
Invalid id format (UUIDs must be of the form "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx", where x is one of [0-9, a-f] M is one of [1-5], and N is [8, 9, a, or b]
Use of a low-quality source of randomness (such as Math.random)
Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the uuid module.
https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid/2117523#2117523
*/
// 36 characters
// xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
/*
* x 0
* x 1
* x 2
* x 3
* x 4
* x 5
* x 6
* x 7
* - 8
* x 9
* x 10
* x 11
* x 12
* - 13
* M 14
* x 15
* x 16
* x 17
* - 18
* N 19
* x 20
* x 21
* x 22
* - 23
* x 24
* x 25
* x 26
* x 27
* x 28
* x 29
* x 30
* x 31
* x 32
* x 33
* x 34
* x 35
*/
function generateUUID() {
const x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'];
const m = [1, 2, 3, 4, 5];
const n = [8, 9, 'a', 'b'];
let uuid = "";
for (var i = 0; i < 36; i++) {
if (i >= 0 && i <= 7) {
// x
uuid += getRandomElementFromArray(x);
} else if (i === 8 || i === 13 || i === 18 || i === 23) {
// dash
uuid += '-';
} else if (i >= 9 && i <= 12) {
// x
uuid += getRandomElementFromArray(x);
} else if (i >= 14 && i <= 17) {
// x
uuid += getRandomElementFromArray(x);
} else if (i === 19) {
// N
uuid += getRandomElementFromArray(n);
} else if (i >= 20 && i <= 22) {
// x
uuid += getRandomElementFromArray(x);
} else if (i >= 24 && i <= 35) {
// x
uuid += getRandomElementFromArray(x);
}
}
return uuid;
}
// https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array
function getRandomElementFromArray(array) {
return array[Math.floor(Math.random() * array.length)];
}
const newUUID = generateUUID();
console.log(`newUUID: ${newUUID}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment