HTML5 Zone is brought to you in partnership with:

My name is Veera. I'm a full stack web developer. I have founded http://www.timethetask.com and currently working on my next product. Veera is a DZone MVB and is not an employee of DZone and has posted 33 posts at DZone. You can read more from them at their website. View Full User Profile

Underscore.js and guid function

01.09.2013
| 3185 views |
  • submit to reddit

Underscore library comes with the uniqueId() function that generates globally unique IDs to use in code. But it was not enough for my Backbone models as I needed the IDs to be unique across  invocations and users, i.e. something like UUID.

I have been using this code snippet to generate pseudo unique IDs for some time. Since it’s a utility function and it made lots of sense to move it to Underscore itself. Here’s how I did it.

_.mixin({
    guid : function(){
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
      });
    }
  });

Once the above code is in place, then creating a unique ID is as simple as calling _.guid().



Published at DZone with permission of Veera Sundar, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)