I was surfing the internet a bit today and starting thinking about universally unique IDs. I came across this site which generates the UUIDs on the server side and then decided to make my own pseudo globally unique ID generator:


(function() {
  // The object literal used to keep track of all of the generated
  // IDs.
  var used = {};
  
  // The globally visible function which is used to generate
  // UUID that are unique for the remainder of the page session.
  getUUID = function(id) {
    for(;used[id = randomHex(8) + "-" + randomHex(4) + "-"
              + randomHex(4) + "-" + randomHex(4) + randomHex(8)];){}
    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.
  function randomHex(len) {
    return (new Array(len).join(0)
            + parseInt(Math.pow(2, len * 4) * Math.random()
                      ).toString(16)).slice(-len);
  }
})();

You can use this function to generate as many UUIDs as you want. As stated in the comments of the code, this function will not generate the same UUID twice in the same session for the page. On the other hand, as pointed out here on stackoverflow.com, a true GUID cannot be generated with JavaScript, but this is good enough for me. 8)

Categories: BlogJavaScriptJScript

1 Comment

Michael J. Ryan · June 22, 2012 at 2:50 PM

Here’s my take on it.. a bit more sound generation of UUIDs in JS.

http://frugalcoder.us/post/2012/01/13/javascript-guid-uuid-generator.aspx

Of course, there’s also node-uuid ….
https://github.com/broofa/node-uuid

Leave a Reply

Your email address will not be published. Required fields are marked *