math.random non repeat same number code example

Example: math.random non repeat same number

let haveIt = [];

function generateUniqueRandom(maxNr) {
    //Generate random number
    let random = (Math.random() * maxNr).toFixed();

    //Coerce to number by boxing
    random = Number(random);

    if(!haveIt.includes(random)) {
        haveIt.push(random);
        return random;
    } else {
        if(haveIt.length < maxNr) {
          //Recursively generate number
         return  generateUniqueRandom(maxNr);
        } else {
          console.log('No more numbers available.')
          return false;
        }
    }
}


console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));

console.log(generateUniqueRandom(10));


console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));


console.log('Unique random numbers:' ,haveIt);