Skip to content

Instantly share code, notes, and snippets.

@velizarn
Last active November 3, 2020 14:56
Show Gist options
  • Save velizarn/0dde94d66bd1f9ba93884ed206a3036b to your computer and use it in GitHub Desktop.
Save velizarn/0dde94d66bd1f9ba93884ed206a3036b to your computer and use it in GitHub Desktop.
Generate UUID v4
/**
* Generates UUID identifier - version 4, variant DCE 1.1, ISO/IEC 11578:1996
*
* @returns {String} - UUID identifier
*
* https://en.wikipedia.org/wiki/Universally_unique_identifier
* https://www.uuidtools.com/decode
* https://www.uuidtools.com/generate/v4
*/
const uuid = () => {
const rand = [...Array(32)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
const variant = ['8', '9', 'a', 'b'];
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/x/g, (c, i) => (`${rand}${rand}`)[i])
.replace('y', variant[Math.floor(Math.random() * variant.length)]);
};
// https://jsfiddle.net/7e3buj4L/
//
// 7089366c-a2e5-4e8b-a5fb-1fc9a5567089
// 06119031-7e14-461b-8ed7-3125563d0611
// e8e784ee-8d13-4458-a385-c9992bc9e8e7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment