Created
September 16, 2022 19:47
-
-
Save IvanAdmaers/7511f886e9902d9d45b078a0d4b4f3a5 to your computer and use it in GitHub Desktop.
Random drop chance JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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