0

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;
Mark
  • 90,562
  • 7
  • 108
  • 148
James
  • 129
  • 2
  • 11
  • 1
    Possible duplicate of [True or better Random numbers with Javascript](https://stackoverflow.com/questions/12673691/true-or-better-random-numbers-with-javascript) – Gregoire Lodi May 19 '18 at 23:29
  • The only way to conclusively avoid repeating random numbers is to keep track of the previously used values and check your random output against the previously used numbers and if found, then make a new random value that isn't in the list. – jfriend00 May 20 '18 at 04:18
  • If you share what you're actually using this random value for, we could better come up with ideas/alternatives. – jfriend00 May 20 '18 at 04:19

1 Answers1

1

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.

  • If your only goal is to get unique numbers and you are not limited concerning the value’s length, use the UTC date representation in millisecs. –  May 20 '18 at 06:02
  • Hi, Thank you for your answer but How do i limit within 5 digit value. The Random value i am looking for must be 5 digit only. – James May 21 '18 at 21:07
  • Hi James, if you are bound to a limit of 5 characters, an increasing number doesn't make sense as you can't prevent repetition. So I edited my answer and put in a better solution referring to your needs. –  May 22 '18 at 06:20