I am making a function that will generate a unique 'x' numbers base on the range & set given.
Examples
- randomizer({ range: 50, set: 5 }) = [8, 16, 32, 40, 48]
- randomizer({ range: 15, set: 3 }) = [4, 11, 15]
- randomizer() = [2, 4, 5, 3, 1]
function randomizer(data) {
const dataRange = data && data.range
? data.range
: 5;
const dataSet = data && data.set
? data.set
: 5;
if (dataRange < dataSet) {
console.log('Range cannot be lower than the Set!');
return;
}
const randomizerRange = [];
for (let r = 1; r <= dataRange; r++) {
randomizerRange.push(r);
}
const randomizerSet = [];
let randomNumber;
for (let s = 1; s <= dataSet; s++) {
randomNumber = Math.floor((Math.random() * (dataRange - s)) + 1);
if (randomizerSet.includes(randomizerRange[randomNumber])) {
/*
make sure that the next number on randomizerSet is unique
this loop is crashing the browser đ
*/
let isUnique = false;
do {
randomNumber = Math.floor((Math.random() * (dataRange - s)) + 1);
if (!randomizerSet.includes(randomizerRange[randomNumber])) {
isUnique = true;
}
} while (!isUnique);
}
randomizerSet.push(randomizerRange[randomNumber]);
}
return randomizerSet;
}
My issue is on the while
loop, the browser is crashing đ
I need help to make sure that the returned array will never have a repeated value? Thank you.
Aucun commentaire:
Enregistrer un commentaire