-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweighted_set.js
71 lines (55 loc) · 1.1 KB
/
weighted_set.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class WeightedSet{
constructor(){
this._map = {};
this._total_weight = 0;
this._total_is_valid = true;
}
add(item, weight){
this._map[item] = weight;
this._total_is_valid = false;
}
remove(item){
delete this._map[item];
this._total_is_valid = false;
}
remove_all(){
this._map = {};
this._total_weight = 0;
this._total_is_valid = true;
}
get_total_weight(){
this._calculate_total_weight();
return this._total_weight;
}
is_empty(){
return this.get_total_weight() == 0;
}
choose_random(){
this._calculate_total_weight()
if (this._total_weight == 0){
return null;
}
let roll = Math.random() * this._total_weight;
let sum = 0;
let safety_net = 0;
for (const [item, weight] of Object.entries(this._map)) {
sum = sum + weight;
if (roll < sum){
return item;
}
safety_net = item;
}
return safety_net;
}
_calculate_total_weight(){
if (this._total_is_valid){
return null;
}
let sum = 0;
for (const [item, weight] of Object.entries(this._map)) {
sum = sum + weight;
}
this._total_weight = sum;
this._total_is_valid = true;
}
}