28 lines
572 B
JavaScript
28 lines
572 B
JavaScript
/**
|
|
* Choose a pair at random among a list of weighted pairs.
|
|
*
|
|
* @param pairs List of weighted pairs, with the weight coming first.
|
|
* @return Selected pair, or null if there is nothing to choose from.
|
|
*/
|
|
export const choose = pairs =>
|
|
{
|
|
const total = pairs.reduce((prev, [weight, _]) => prev + weight, 0);
|
|
|
|
if (total === 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
const value = Math.random() * total;
|
|
let sum = 0;
|
|
let index = 0;
|
|
|
|
while (value >= sum)
|
|
{
|
|
sum += pairs[index][0];
|
|
index += 1;
|
|
}
|
|
|
|
return pairs[index - 1];
|
|
};
|