DEV Community

loading...

Discussion on: Generators in Javascript: How to use them

Collapse
lcfvs profile image
Lcf.vs

Better distinctRandom:

function* distinctRandom({limit = 10}) {
  // we create an array that contains all numbers in range [0:limit)
  // this is our initial pool of numbers to choose from
  const availableValues = [...new Array(limit).keys()];

  // we repeatedly loop until the available pool of numbers is empty
  while (availableValues.length !== 0) {
    // generate a random index in range [0: availableValues.length)
    // then, yield the number that is present at the chosen index
    // Finally, remove the picked item from the pool of available numbers
    const currentRandom = Math.floor(Math.random() * availableValues.length);
    yield availableValues.splice(currentRandom, 1)[0];
  }
}
Enter fullscreen mode Exit fullscreen mode