Skip to content

Instantly share code, notes, and snippets.

@alivesay
Last active January 3, 2016 00:19
Show Gist options
  • Save alivesay/8381931 to your computer and use it in GitHub Desktop.
Save alivesay/8381931 to your computer and use it in GitHub Desktop.
Fast Javascript RFC-compliant UUID generator.
/**
* Generates an RFC4122-compliant v4 UUID.
* @returns {string}
*/
function generateUUID() {
var timestamp = Date.now(), uuid = '', i = 36, c,
hexChars = '0123456789abcdef',
uuidPattern = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
while (i--) {
c = uuidPattern.charAt(i);
if (c === 'x') {
uuid = hexChars.charAt(timestamp + Math.random() * 0xFF & 15)) + uuid;
} else if (c === '-' || c === '4') {
uuid = c + uuid;
} else {
uuid = hexChars.charAt(Math.random() * 4 + 8 | 0) + uuid;
}
timestamp >>= 2;
}
return uuid;
}
@sukima
Copy link

sukima commented Aug 5, 2014

Line 13 has a syntax error (parentheses).

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