Search code examples
javascriptnode.jstypescriptjavascript-objects

How to create a unique value each time when ever I run the java-script code?


I am using Math.random to create a unique value. However , it looks like after some days , if i run the same script it produces the same value that created earlier.

Is there any way to create unique value every time when ever i run the script. Below is my code for the random method.

var RandomNo = function (Min,Max){
    return Math.floor(Math.random() * (Max - Min + 1)) + Min;
}

module.exports = RandomNo;

Solution

  • The best way to achieve a unique value is to use Date() as milliseconds. This increasing time representation will never repeat.

    Do it this way:

    var RamdomNo = new Date().getTime();
    

    Done.

    Edit

    If you are bound to length restrictions, the solution above won't help you as repetition is predictable using an increasing number the shorter it gets.

    Then I'd suggest the following approach:

    // turn Integer into String. String length = 36
    function dec2string (dec) {
      return ('0' + dec.toString(36)).substr(-2);
    }
    
    // generate a 20 * 2 characters long random string
    function generateId () {
      var arr = new Uint8Array(20);
      window.crypto.getRandomValues(arr);
    
      // return 5 characters of this string starting from position 8.
      // here one can increase the quality of randomness by varying
      // the position (currently static 8) by another random number <= 35
      return Array.from(arr, this.dec2string).join('').substr(8,5);
    }
    
    // Test
    console.log(generateId());
    

    This pair of methods generates a 40 characters long random string consisting of letters and digits. Then you pick a sequence of 5 consecutive characters off it.