Skip to content

Instantly share code, notes, and snippets.

@IvanAdmaers
Created September 16, 2022 19:47
Show Gist options
  • Save IvanAdmaers/7511f886e9902d9d45b078a0d4b4f3a5 to your computer and use it in GitHub Desktop.
Save IvanAdmaers/7511f886e9902d9d45b078a0d4b4f3a5 to your computer and use it in GitHub Desktop.
Random drop chance JS
const items = [
{
name: 'Apple',
dropChance: 0.7
},
{
name: 'Knife',
dropChance: 0.25
},
{
name: 'Spoon',
dropChance: 0.25
},
{
name: 'Ice Cream',
dropChance: 0.1
}
];
const lerp = (min, max, value) => ((1 - value) * min + value * max);
const drop = items => {
const total = items.reduce((accumulator, item) => (accumulator += item.dropChance), 0);
const chance = lerp(0, total, Math.random());
let current = 0;
for (const item of items) {
if (current <= chance && chance < current + item.dropChance) {
return item;
}
current += item.dropChance;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment