6

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 ?

7
  • 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) Commented Apr 3, 2019 at 8:53
  • Possible duplicate of Unique (non-repeating) random numbers in O(1)? Commented Apr 3, 2019 at 8:55
  • Also relevant: stackoverflow.com/questions/2380019/… althought the accepted answer is not the best. Commented Apr 3, 2019 at 8: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... Commented Apr 3, 2019 at 8:57
  • This will deal with uniqueness 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 ;) Commented Apr 3, 2019 at 9:02

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

0

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

2 Comments

var datetimestamp = Date.now() + Math.random().toString(36).substr(2, 9);
Does it give unique random number every second?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.