mirror of
https://gitea.wildfiregames.com/0ad/0ad
synced 2026-06-18 14:23:56 -07:00
eslint --no-config-lookup --fix --rule '"prefer-const": 1' \
binaries/data/mods/public/globalscripts
Ref: #7812
Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
37 lines
738 B
JavaScript
37 lines
738 B
JavaScript
function WeightedList()
|
|
{
|
|
this.elements = new Map();
|
|
this.totalWeight = 0;
|
|
}
|
|
|
|
WeightedList.prototype.length = function()
|
|
{
|
|
return this.elements.size;
|
|
};
|
|
|
|
WeightedList.prototype.push = function(item, weight = 1)
|
|
{
|
|
this.elements.set(item, weight);
|
|
this.totalWeight += weight;
|
|
};
|
|
|
|
WeightedList.prototype.remove = function(item)
|
|
{
|
|
const weight = this.elements.get(item);
|
|
if (weight)
|
|
this.totalWeight -= weight;
|
|
this.elements.delete(item);
|
|
};
|
|
|
|
WeightedList.prototype.randomItem = function()
|
|
{
|
|
const targetWeight = randFloat(0, this.totalWeight);
|
|
let cumulativeWeight = 0;
|
|
for (const [item, weight] of this.elements)
|
|
{
|
|
cumulativeWeight += weight;
|
|
if (cumulativeWeight >= targetWeight)
|
|
return item;
|
|
}
|
|
return undefined;
|
|
};
|