Created
May 22, 2013 06:39
-
-
Save crodjer/5625668 to your computer and use it in GitHub Desktop.
Javascript UUIDs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function uuids (count, seed) { | |
var pattern = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; | |
var _uuids = []; | |
if (count === undefined) { | |
count = 1; | |
} | |
if (seed === undefined) { | |
seed = 1; | |
} | |
if (count < 1 && count > 0) { | |
seed = count; | |
count = 1; | |
} | |
if (count <= 0) { | |
throw 'Count should be greater than 0'; | |
} | |
if (seed <= 0 || seed > 1) { | |
throw 'Seed should be in greater than 0 and less than or equal to 1'; | |
} | |
function getUUID(pattern) { | |
// Borrowed from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 | |
return pattern.replace(/[xy]/g, function(character) { | |
var seeded_rand; | |
var raw_rand = Math.random(); | |
var max = Math.max(raw_rand, seed); | |
var min = Math.min(raw_rand, seed); | |
if (max === 0) { | |
seeded_rand = 0; | |
} else { | |
/* This is required to ensure that either of the numbers don't decrease | |
the range of set size. That is why seed * raw_rand will not be right. */ | |
seeded_rand = min/max; | |
} | |
var ranged_rand = seeded_rand*16|0; | |
var replacement = character === 'x' ? ranged_rand : (ranged_rand & 0x3|0x8); | |
return replacement.toString(16); | |
}); | |
} | |
// Fill up uuids upto the count which is asked for | |
while(_uuids.push(getUUID(pattern)) < count) { | |
} | |
return _uuids; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment