I'm trying to come up with a self-contained pseudo-random number generator function which will not repeat the previous output.
The obvious not self contained solution would be:
let lastX = -1;
function uniqueNumber(range) {
let x = Math.round(Math.random() * range - 0.5);
if (lastX == x) return uniqueNumber(range);
else {
lastX = x;
return x;
}
}
for (let i = 0; i < 10; i++) {
console.log(uniqueNumber(5))
}
However I'd like the function to be self contained and having the variable outside of the function seems rough. We could encapsulate the variable and function into a object but I'm trying to come up with a self contained function.
I've came up with a solution using the browser storage as a pseudo memory, but it feels a bit overkill using long term storage as temporary memory:
function uniqueNumber(range) {
let lastX
if(localStorage.getItem('numberwang') === null) lastX = -1;
else lastX = localStorage.getItem('numberwang')
let x = Math.round(Math.random() * range - 0.5);
if (lastX == x) return uniqueNumber(range);
else {
localStorage.setItem('numberwang', x)
lastX = x;
return x;
}
}
for (let i = 0; i < 10; i++) {
console.log(uniqueNumber(5))
}
Is there a more subtle way to achieve the same outcome, like possibly saving the last result to a RAM address?