@roninjjj/randomize
Version:
Easily include random number generation in your projects. Whether if it's a 2 item 50/50, or a 20 item lootbox, all you need is a simple object!
25 lines (24 loc) • 976 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
function randomChance(chances) {
const chance_sum = Object.values(chances)
.reduce((acc, curr) => acc + curr);
if (chance_sum !== 100)
throw new Error(`Incorrect percentages. Received ${chance_sum} while expecting 100.`);
const rand = Math.random() * 100; // a number between 0 and 99.9
let _ = 0;
const pairs = Object.entries(chances).sort((a, b) => b[1] - a[1]) // { gold: 10, silver: 90 } -> [ ['silver', 90], ['gold', 10] ]
.reduce((acc, curr) => {
_ += curr[1];
acc.push([curr[0], _]);
return acc;
}, []); // [ ['silver', 90], ['gold', 10] ] -> [ ['silver', 90], ['gold', 100] ]
for (const [value, chance] of pairs) {
if (chance > rand) {
return value;
}
}
// in case of any unexpected outputs, return the most common item.
return pairs[0][0];
}
exports.default = randomChance;