Skip to content

Instantly share code, notes, and snippets.

@knalli
Created December 31, 2012 15:40
Show Gist options
  • Save knalli/4420776 to your computer and use it in GitHub Desktop.
Save knalli/4420776 to your computer and use it in GitHub Desktop.
Create an UUID in JavaScript
var buildUUID = function(bits) {
var CHARS, i, rand, result, _i;
CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ012345678900';
result = '';
while (bits > 0) {
rand = Math.floor(Math.random() * 0x100000000);
for (i = _i = 26; _i > 0; i = _i += -6) {
result += CHARS[0x3F & rand >>> i];
bits -= 6;
if (!(bits > 0)) {
break;
}
}
}
return result;
};
// Test (256 Bits, 8 Bits per Byte, so 32 Bytes)
var uuid = buildUUID(256);
uuid.should.have.a.length.of(32)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment