0

I'm trying to generate an ID, but I do not want any duplicates (Obviously), so is there a way to loop a function until an unused ID is found?

Here's the current Code I'm trying to use:

Obviously there'll be more than just 10 IDs, but this is just for simplicity sake

let used_IDs = [1, 2, 3, 5, 6, 7, 8, 9, 10];

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

let newID = randomID(1, 10);

if (used_IDs.includes(newID)) {

  new ID = randomID(1, 10);
  return console.log('Your new ID is ' + newID);

} else {

  return console.log('Your new ID is ' + newID);

}

The problem with this code is that it'll only work once. How do I loop it? To make sure another duplicate doesn't occur?

Yazuki Rin
  • 113
  • 1
  • 12
  • "*I'm trying to generate an ID, but I do not want any duplicates*" why not [generate a GUID](https://stackoverflow.com/questions/105034/how-to-create-guid-uuid)? – VLAZ May 07 '20 at 12:26
  • Also, if you're generating sequential IDs, then why not do `max+`? Or if you want them from a random range, you can generate all IDs in the range, shuffle, then take off ones until you're finished. – VLAZ May 07 '20 at 12:29

1 Answers1

1

You can use a while loop to loop until you've found a unique random ID.

function getRandomUid() {
  let newID = randomID(1, 10);
  while (used_IDs.includes(newID)) {
    newID = randomID(1, 10);
  }
  console.log('Your new ID is ' + newID);
  // don't forget to update used_IDs here.
  return newID;
}

Also, it might be better if you use Set for used_IDs instead of an Array, as it's faster and guarantees you never add duplicate.

Also, remember if you run above code a few times with hardcoded parameters (1 and 10), you'll soon run out of unique ids and get an infinite loop. It's better to use a UUID generator if you want actually unique IDs in a safe manner.

Sid Vishnoi
  • 1,250
  • 1
  • 16
  • 27
  • 1
    "*Also, remember if you run above code a few times with hardcoded parameters (1 and 10), you'll soon run out of unique ids*" fun fact, because of the [birthday paradox](https://en.wikipedia.org/wiki/Birthday_problem) you only ever have until around square root of the total number until the chance for a clash becomes 50%. So, with a total number of 10 IDs, you need `sqrt(10) ≈ 2` picks before you run into 50% chance to generate a duplicate. – VLAZ May 07 '20 at 12:33