Last change
on this file since 25276 was 25276, checked in by Freagarach, 3 years ago |
Use a map for the weighted list.
Less object creations at addition time, more intuitive handling.
Differential revision: https://code.wildfiregames.com/D3854
Comments by: @Stan, @wraitii
|
-
Property svn:eol-style
set to
native
|
File size:
791 bytes
|
Line | |
---|
1 | function WeightedList()
|
---|
2 | {
|
---|
3 | this.elements = new Map();
|
---|
4 | this.totalWeight = 0;
|
---|
5 | };
|
---|
6 |
|
---|
7 | WeightedList.prototype.length = function()
|
---|
8 | {
|
---|
9 | return this.elements.size;
|
---|
10 | };
|
---|
11 |
|
---|
12 | WeightedList.prototype.push = function(item, weight = 1)
|
---|
13 | {
|
---|
14 | this.elements.set(item, weight);
|
---|
15 | this.totalWeight += weight;
|
---|
16 | };
|
---|
17 |
|
---|
18 | WeightedList.prototype.remove = function(item)
|
---|
19 | {
|
---|
20 | const weight = this.elements.get(item);
|
---|
21 | if (weight)
|
---|
22 | this.totalWeight -= weight;
|
---|
23 | this.elements.delete(item);
|
---|
24 | };
|
---|
25 |
|
---|
26 | WeightedList.prototype.randomItem = function()
|
---|
27 | {
|
---|
28 | const targetWeight = randFloat(0, this.totalWeight);
|
---|
29 | let cumulativeWeight = 0;
|
---|
30 | for (let [item, weight] of this.elements)
|
---|
31 | {
|
---|
32 | cumulativeWeight += weight;
|
---|
33 | if (cumulativeWeight >= targetWeight)
|
---|
34 | return item;
|
---|
35 | }
|
---|
36 | return undefined;
|
---|
37 | };
|
---|
38 |
|
---|
39 | Engine.RegisterGlobal("WeightedList", WeightedList);
|
---|
Note:
See
TracBrowser
for help on using the repository browser.