My solution uses Set to retain the uniqueness of the values:
const getRangeRandomizer = ([min, max]) => { // create the range randomizer
const state = new Set(); // the numbers that were produced from the range
/** the returned method can be used to get more numbers from the range **/
return (numOfRandoms) => {
const discarded = new Set(); // this Set is used to count numbers that are not unique
const range = max - min + 1;
const result = [];
let i = 0;
let randNum;
while (i < numOfRandoms && discarded.size < range) { // if we added numOfRandoms times or we discarded delta optionsm the loop end - this prevents endless loops
randNum = Math.floor(Math.random() * (range) + min);
if (state.has(randNum)) {
discarded.add(randNum);
} else {
state.add(randNum);
result.push(randNum);
i++;
}
}
return result;
}
}
const provideRanges = getRangeRandomizer([10, 20]); // create a range randomizer
console.log(provideRanges(4));
console.log(provideRanges(3));
console.log(provideRanges(2));
console.log(provideRanges(4)); // only 2 results will be provided, because the rest were used
const provideOtherRanges = getRangeRandomizer([15, 20]); // create a range randomizer
console.log(provideOtherRanges(100));