Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Underscore.js and guid function

DZone's Guide to

Underscore.js and guid function

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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



Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}