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?
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()); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With