Skip to content

Instantly share code, notes, and snippets.

@moskalyk
Created July 17, 2024 13:55
Show Gist options
  • Save moskalyk/288bf95c553ff5fdaf0b5026b943a3b0 to your computer and use it in GitHub Desktop.
Save moskalyk/288bf95c553ff5fdaf0b5026b943a3b0 to your computer and use it in GitHub Desktop.
function getRandomRarity(rarities) {
// Convert rarities object to an array of [key, value] pairs
const entries = Object.entries(rarities);
// Sum of all probabilities
const totalProbability = entries.reduce((sum, [, probability]) => sum + probability, 0);
// Normalize the probabilities to ensure they sum up to 1
if (totalProbability !== 1) {
throw new Error("Total probability must sum up to 1");
}
// Generate a random number between 0 and 1
const random = Math.random();
let cumulativeProbability = 0;
// Iterate over the entries to find the corresponding key
for (const [key, probability] of entries) {
cumulativeProbability += probability;
if (random < cumulativeProbability) {
return key;
}
}
// Fallback in case of any floating-point arithmetic issues
return entries[entries.length - 1][0];
}
// Example usage
const rarities = {
rare: 0.1,
legendary: 0.05,
common: 0.5,
uncommon: 0.35
};
const randomRarity = getRandomRarity(rarities);
console.log(randomRarity); // Output could be "common", "uncommon", "rare", or "legendary"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment