原始问题:
这是我的问题,我有一个登录帐户时需要使用的令牌列表,可以完全随机分配这些项目,但我想删除我使用了大约30秒钟的令牌,因为在此期间该帐户正在使用中,其他任何人都不能使用。我如何能够在一段时间内从数组中删除令牌,并在x时间后将其放回数组中? (30秒)。
我想到的解决方案:
我创建了2个函数,一个函数从数组中检索随机令牌,而另一个函数实际上执行删除该令牌并将其放置在x时间内(30秒)内的函数]
我的代码:
const tokens = ["Token1", "Token2", "Token3"]; // Tokens
function runToken(index, value) { // Does the work of removing the element from the array and placing it back in the array.
tokens.splice(index, 1); // Removes the chosen token from the array
setTimeout(() => { // waits 5 seconds to push the array element back
tokens.push(value); // Action to push it back
}, 30000);
}
function getActiveToken() { // Function to use in order to get the item from the array
let chosenToken = tokens[Math.floor(Math.random() * tokens.length)]; // Chooses a random element avaliable in the array
let chosenTokenIndex = tokens.indexOf(chosenToken); // Retrieves the index for use later
runToken(chosenTokenIndex, chosenToken); // Runs the function above to remove the token and push it back later
return chosenToken; // Returns the token so that you can use it.
}
console.log(getActiveToken());
//-- "Token1"
如果您有更有效的方法,我希望看到它!
随着阵列大小的增加,添加和删除项目可能会成为昂贵的操作。因此,作为这种情况下的替代方案,我们可以使用“交换”。每当我们随机选择一个项目时,将其与最后一个元素交换,并将其从选择范围中排除特定的时间。