I have the following function that can pull out a random index from an array without repeating the index and keeps pulling them out until all have been used and then resets itself and starts re-using them. It also tries to make sure that the last one that was pulled out isn't the same as the next one pulled out on the reset so that you don't ever have the same index come out in a row.
var listIndexes = [];
var lastIndex;
function getRandomIndex(indexes)
{
if (!listIndexes.length) {
for (var i = 0; i < indexes; i++) {
listIndexes.push(i);
}
}
var randomIndex = Math.floor(Math.random() * listIndexes.length);
var uniqueIndex = listIndexes[randomIndex];
listIndexes.splice(randomIndex, 1);
if(lastIndex && uniqueIndex == lastIndex)
{
listIndexes = [];
getRandomIndex(indexes);
return;
}
lastIndex = uniqueIndex;
return uniqueIndex;
}
var index = getRandomIndex(5);
console.log(index);
However when it hits the code: if(lastIndex && uniqueIndex == lastIndex) it causes it to return undefined for the index. So the way I'm trying to exit the function and re-call the function to try again isn't working as planned.
How can I exit the current function call and re-call the function to get a new random index that isn't the same as the lastIndex. Note that the lastIndex is kept intact until the new index isn't the same regardless of how many times the function is called.