Over a million developers have joined DZone.

Underscore.js and guid function

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

    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().

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Veera Sundar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}