-1

Wondering if this function is reliable to always be unique, also wondering if I should do this locally or on the server?

 function IDGenerator() {

     this.length = 8;
     this.timestamp = +new Date;

     var _getRandomInt = function( min, max ) {
        return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
     }

     this.generate = function() {
         var ts = this.timestamp.toString();
         var parts = ts.split( "" ).reverse();
         var id = "";

         for( var i = 0; i < this.length; ++i ) {
            var index = _getRandomInt( 0, parts.length - 1 );
            id += parts[index];  
         }

         return id;
     }


 }
farhan
  • 233
  • 1
  • 13
  • 2
    It's technically impossible to be _always_ unique when your input and output are finite sets. – zerkms Feb 08 '19 at 03:33
  • 2
    Possible duplicate of [Create GUID / UUID in JavaScript?](https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript) – tripulse Feb 08 '19 at 04:04
  • 1
    A simple counter would have less risk of collision... Can you define what is the scope of this function? Should it be unique per document's life or for every user at any time? – Kaiido Feb 08 '19 at 04:23

2 Answers2

0

Since no two time-stamps can be generated within the same time on the same machine.

Generated by, and within the same machine - a Time-stamp alone - is guaranteed to be Unique.

Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26
  • But they are not using the timestamp as is, they do generate a pseudo-random string using each digit found in the timestamp as upper limit for Math.random() (for I don't know what reason...) – Kaiido Feb 08 '19 at 04:22
0

The problem with just using Math.random is that it is not truly random. On the other hand, the problem with just using a date-time stamp is that, depending on how quickly the method is executed, the value may duplicate.

I have used this to great effect in many applications. It is simple, and I have never come across a conflict due to duplicate values:

function uid() {
    return (Date.now().toString(36) + Math.random().toString(36).substr(2, 9));
}
xcopy
  • 2,248
  • 18
  • 24