I want to run a function that each time randomly chooses an element from an array that wasn\'t chosen before. And if all elements were chosen, I want to reset the used eleme
The easiest way to handle this is:
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var items = ["alpha", "beta", "gamma", "delta", "epsilon"];
var index = Infinity;
function start() {
console.log("----- shuffling -----")
shuffle(items);
index = 0;
}
function nextItem() {
if (index >= items.length) {
//re-start
start()
}
//return current index and increment
return items[index++];
}
document.getElementById("click_me")
.addEventListener("click", function() {
console.log(nextItem())
})
This can also be converted to a generator function
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function* random(array) {
let index = Infinity;
const items = array.slice(); //take a copy of the array;
while(true) {
if (index >= array.length) {
console.log("----- shuffling -----")
shuffle(items);
index = 0;
}
yield items[index++];
}
}
var items = ["alpha", "beta", "gamma", "delta", "epsilon"];
//start the generator
const generateRandom = random(items);
document.getElementById("click_me")
.addEventListener("click", function() {
console.log(generateRandom.next().value)
})