The problem is that you have a number of drugs and you want to move them all in an array of similar size. random, might take a long time to actually get 13 distinct indexes.
For example if we have 13 drugs and we want to get 12 drugs in the result array, random will have to generate 12 distinct numbers, in the 1-13 range, it may take a long time to get all of them, random guarantees randomness not fair distribution. In large sets you will get all numbers, but the key is large
A better approach would be to copy the array and perform random swaps and then take the amount you need. This guarantees the time it takes is the same regardless of what random generates:
getDrugsForSale() {
let max = this.drugNames.length;
let result = this.drugNames.slice(0);
for (let i = 0; i < 30; i++) {
let source = Math.floor(Math.random() * (max - 1) - 0);
let dest = Math.floor(Math.random() * (max - 1) - 0);
let aux = result[source];
result[source] = result[dest];
result[dest] = aux;
}
return result.slice(0, this.locations[this.currentLocation].numDrugs);
}
Note A simple proof of the fact that it will not generate all the numbers easily, would be to put a console.log(i) in the original code and see the output.
numDrugs?drugNamesarray how big is it ?