Last active
October 28, 2021 00:52
-
-
Save ySnoopyDogy/0dd441c61c38a9a410e85cf4ade5de9c to your computer and use it in GitHub Desktop.
A function that return an element among other elements based on a set probability for each one
This file contains hidden or 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
interface ProbabilityProps<T> { | |
probability: number; | |
value: T; | |
} | |
// Input Example: | |
/* calculateProbability([ | |
{value: 'Cat', probability: 29}, | |
{value: 'Dog', probability: 50}, | |
{value: 'Fish', probability: 20}, | |
{value: 'Unicorn', probability: 1} | |
]) | |
*/ | |
const calculateProbability = <T>(probabilities: Array<ProbabilityProps<T>>): T => { | |
const chance = Math.floor(Math.random() * 100); | |
let accumulator = probabilities.reduce((p, c) => p + c.probabilty, 0); | |
const mapedChanges: { amount: number; probabilities: number[] }[] = probabilities.map((a) => { | |
const toReturn = [accumulator - a.probabilty, accumulator]; | |
accumulator -= a.probabilty; | |
return { value: a.value, probabilities: toReturn }; | |
}); | |
for (const data of mapedChanges) { | |
const [min, max] = data.probabilities; | |
if (chance >= min && chance <= max) { | |
return data.value; | |
} | |
} | |
return 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment