Created
November 3, 2020 01:39
-
-
Save danman113/f798022236488d463c251177dc66cbfe to your computer and use it in GitHub Desktop.
Probability Map
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
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