weighted-random-object
Version:
Get a weighted random object from an array of objects.
18 lines (17 loc) • 523 B
JavaScript
;
/**
* Get a weighted random object from an array of objects with a weight property.
*
* The objects should have a property with key 'weight' and a value that is a number.
*/
module.exports = function (objects) {
var totalWeight = objects.reduce(function (agg, object) {
return agg + object.weight;
}, 0);
var randomNumber = Math.random() * totalWeight;
var weightSum = 0;
return objects.find(function (object) {
weightSum += object.weight;
return randomNumber <= weightSum;
});
};