4

I need to get unique random number in javascript (or Typescript).

At this moment I use this code:

var id = -((new Date()).getTime() & 0xffff);

It returns me numbers like -13915 or -28806 ...

It works most of the time but I am having problems when this code is executed in promises (so nearly multiple times at the same time). Then sometimes I got two identical id.

Is there any solution to get unique random numbers in any case ?

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
Bronzato
  • 9,438
  • 29
  • 120
  • 212
  • This is not C where you have to use time as seed. You can use `Math.random()` (which is probably time-seeded too, but it's way better than your approach) – Christian Vincenzo Traina Apr 03 '19 at 08:53
  • Possible duplicate of [Unique (non-repeating) random numbers in O(1)?](https://stackoverflow.com/questions/196017/unique-non-repeating-random-numbers-in-o1) – VLAZ Apr 03 '19 at 08:55
  • Also relevant: https://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100 althought the accepted answer is not the best. – VLAZ Apr 03 '19 at 08:56
  • @CristianTraìna `Math.random()` is not guaranteed to give you unique numbers. I really don't know why this needs to be repeated so many times... – VLAZ Apr 03 '19 at 08:57
  • This will deal with uniqueness [Create GUID / UUID in JavaScript?](https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript), then you can transform it to a number if you need another format, but I think the uniqueness spirit should come from overthere ;) – sjahan Apr 03 '19 at 09:02
  • Another option is to generate a [globally unique identifier (GUID)](https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript). Technically, they *could* clash but chances are astronomically low. – VLAZ Apr 03 '19 at 09:03
  • Yet another consideration - do you really need *random* values or *distinct* values? Because you could use a timestamp - then the value would not overlap with another. But it's not "random". – VLAZ Apr 03 '19 at 09:08

5 Answers5

5

There are many examples around internet. You can start with using Math.random() . For example: generate random number between 1 and 100

Math.floor((Math.random() * 100) + 1);

Just keep in mind that it is not truly random; it is not cryptographically secure. You should probably look into libraries if you need that

Mr Shumar
  • 251
  • 1
  • 4
1

Create a function that returns a unique number:

let numbers = [];

const uniqueNumber = (maxVal) => {
   const number = Math.floor((Math.random() * maxVal) + 1);
   if (!numbers.includes(number)) {
      numbers.push(number);
      return number;
   } else if (numbers.length - 1 !== maxVal) {
      uniqueNumber(maxVal);
   }
}

const randomNumber = uniqueNumber(100);
console.log(numbers) // returns all unique numbers

This will return a unqiue number between 1 and 100. It also stops at the max length.

Dennis Spierenburg
  • 613
  • 2
  • 6
  • 16
1

You can use the package uuid:

const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ '10ba038e-48da-487b-96e8-8d3b99b6d18a'

Notice: It is a number (a 128-bit number) but it is too big to be used as a JavaScript number. You have to keep it as a string.

If you need it on the browser, I suggest to generate the identifier from an API exposed on your back-end. Implementations of UUID exist in most of languages. The npm package will work on browsers but then it uses a fallback to Math.random, which is not secure.

See also: Universally unique identifier.

Paleo
  • 21,831
  • 4
  • 65
  • 76
0

var datetimestamp = Date.now() + Math.random().toString(36).substr(2, 9);

0
  1. Math.random() in itself should be safe enough, what with 64-bit numbers. Even with imperfect generator, the chances of hitting the same number twice are minuscule.

  2. If you're after specifically integers, then multiply Math.random() by something BIG, like Number.MAX_SAFE_INTEGER.

  3. To be perfectly safe, you can always store an array of already used ids, and write a function that draws as long as gets a new unique number, pushes it into array, and returns the value. Enclose all that functionality inside a single object/function/class, to keep it neat.

mbojko
  • 13,503
  • 1
  • 16
  • 26