Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Globally Unique ID in JavaScript [duplicate]

Tags:

javascript

I have a script that, when a user loads, creates a unique id. Which is then saved in localStorage and used for tracking transactions. Sort of like using a cookie, except since the browser is generating the unique id there might be collisions when sent to the server. Right now I'm using the following code:

function genID() {     return Math.random().toString(36).substr(2)         + Math.random().toString(36).substr(2)         + Math.random().toString(36).substr(2)         + Math.random().toString(36).substr(2); } 

I realize this is a super basic implementation, and want some feedback on better ways to create a "more random" id that will prevent collisions on the server. Any ideas?

like image 276
Trevor Norris Avatar asked Aug 31 '12 23:08

Trevor Norris


1 Answers

I've used this in the past. Collision odds should be very low.

var generateUid = function (separator) {     /// <summary>     ///    Creates a unique id for identification purposes.     /// </summary>     /// <param name="separator" type="String" optional="true">     /// The optional separator for grouping the generated segmants: default "-".         /// </param>      var delim = separator || "-";      function S4() {         return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);     }      return (S4() + S4() + delim + S4() + delim + S4() + delim + S4() + delim + S4() + S4() + S4()); }; 
like image 190
James South Avatar answered Sep 21 '22 13:09

James South