You can use a seedable random numbers generator like seedrandom
How it works:
Every random number generator is only a psuedo random generator, meaning nothing is really random here, even for Math.random
- it's just some crazy algorithm that generates numbers by a given input.
But javascript seeds Math with its own variables and doesn't allow us to seed it ourself (like we can in c for example) - that's where seedrandom comes in, it's just a simple custom random number generator for javascript, which also happens to accept strings as a seed (good for your needs).
We feed the random number generator a custom seed (user id/session) which allows us to have a predictable random number generator - so for example if the first call produce 0.2, and the second call produce 0.5 - we can be sure that if the user refreshes the page and we give the same seed, the first number will always be 0.2 and the second number will always be 0.5.
How to use:
The use is pretty easy:
// Make a predictable pseudorandom number generator.
const seedrandom = require('seedrandom');
const myRandom = seedrandom(sessionID);
console.log(myRandom()); // Always 0.9282578795792454
// example
const pickRandomForUser = (items) => {
const predictableRandom = myRandom();
const randomIndex = Math.floor(predictableRandom * items.length);
return items[randomIndex];
}
const numbers = [12, 24, 89, 09, 43, 99];
// will stay the same for each session id, in this order
const firstRand = pickRandomForUser(numbers)// 12
const secondRand = pickRandomForUser(numbers)// 89