Skip to content

Instantly share code, notes, and snippets.

@theonlydaleking
Last active November 27, 2018 07:11
Show Gist options
  • Save theonlydaleking/9cd4e9d93968a29d8cad5263525fa43f to your computer and use it in GitHub Desktop.
Save theonlydaleking/9cd4e9d93968a29d8cad5263525fa43f to your computer and use it in GitHub Desktop.
weighted allocation example
/*
This can be used when we need to move to a front end that only delivers the
users and their allocation percentage
salesReps is the sample array we would get from the DB.
*/
const salesReps = [
{name: "Renee", id:"30761006", allocation: 70},
{name: "Emma", id:"33620479", allocation: 10},
{name: "Marian", id:"33495420", allocation: 10},
{name: "Jade", id:"30455396", allocation: 10},
]
let weightTotal = salesReps.reduce((tally, rep) => {
return tally += rep.allocation
}, 0)
const allocateRep = () => {
let luckyNumber = Math.floor(Math.random() * weightTotal)
return salesReps.find(rep => {
luckyNumber -= rep.allocation
if (luckyNumber <= 0) {
return rep.name
}
})
}
// Proof
const test = () => {
index = 0
itterations = 10000000
results = []
while (index++ < itterations) {
results.push(allocateRep().name)
}
const count = results.reduce((tally, result) => {
tally[result] = (tally[result] || 0) + 1
return tally
}, {})
console.log(count)
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment