0ad/binaries/data/mods/public/globalscripts/WeightedList.js
Ralph Sennhauser 0791504491
Fix eslint rule 'prefer-const' in globalscripts
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>
2025-05-06 14:16:42 +02:00

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;
};