Skip to content

Instantly share code, notes, and snippets.

@m-mujica
Last active December 13, 2015 20:39
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 m-mujica/4971762 to your computer and use it in GitHub Desktop.
Save m-mujica/4971762 to your computer and use it in GitHub Desktop.
var UUID = function() {
// The object literal used to keep track of all of the generated IDs.
this.used = {};
};
// The globally visible function which is used to generate
// UUID that are unique for the remainder of the page session.
UUID.prototype.generate = function(id) {
for(;this.used[id = this.randomHex(8) + "-" + this.randomHex(4) + "-"
+ this.randomHex(4) + "-" + this.randomHex(4) + this.randomHex(8)];){}
this.used[id] = 1;
return id;
}
// Used to generate a hex number which is padded by zeros to
// display the specified amount of digits. The param passed
// probably shouldn't be more than 8.
UUID.prototype.randomHex = function(len) {
return (new Array(len).join(0)
+ parseInt(Math.pow(2, len * 4) * Math.random()
).toString(16)).slice(-len);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment