Skip to content

Instantly share code, notes, and snippets.

@danman113
Created November 3, 2020 01:39
Show Gist options
  • Save danman113/f798022236488d463c251177dc66cbfe to your computer and use it in GitHub Desktop.
Save danman113/f798022236488d463c251177dc66cbfe to your computer and use it in GitHub Desktop.
Probability Map
class ProbabilityMap {
constructor (map) { // map = {foo: 32, bar: 21}
this.calculateSize = () => {
let count = 0
for (let [,value] of this.set) {
count += value
}
return count
}
this.set = map ? new Map(Object.entries(map)) : new Map()
this.size = map ? this.calculateSize() : 0
this.increment = (key) => {
this.size++
if (this.set.has(key)) this.set.set(key, this.set.get(key) + 1)
else this.set.set(key, 1)
}
this.pick = () => {
let pick = this.size * Math.random()
for (let [key, value] of this.set) {
pick -= value
if (pick < 0) return key
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment