Skip to content

Instantly share code, notes, and snippets.

@jankuca
Created January 21, 2011 08:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jankuca/789412 to your computer and use it in GitHub Desktop.
Save jankuca/789412 to your computer and use it in GitHub Desktop.
UUID JavaScript library; based on the current timestamp, the user's browser, the current URL and a random number
goog.provide('uuid');
var uuid = function () {
var parts = new Array(4);
// a - unix timestamp
var time = Math.round(new Date().getTime() / 1000);
parts[0] = time.toString(16).substring(0, 8);
// b - browser
var ua_string = window.navigator.userAgent;
var match = ua_string.match(/\d+/g);
if (!match) {
throw 'Invalid browser version string';
}
var sum = 0;
for (var i = 0, ii = match.length; i < ii; ++i) {
sum += parseInt(match[i], 10);
}
parts[1] = (sum * sum * sum).toString(16).substring(0, 6);
// c - url
var href = window.location.href;
parts[2] = (href.length * href.length * href.length).toString(16).substring(0, 4);
// d - random
parts[3] = Math.random().toString().substring(2);
parts[3] = parseInt(parts[3], 10).toString(16).substring(0, 6);
return parts.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment