Something like
const items = [ "foo", "bar" ];
const weights = [ 1, 2 ];
const result = scl.weightedRandom(items, weights);
would return a random entry of the items
array, but the RNG should be modified, so that "bar"
is 200% likely to occur, while "foo"
is only at 100%, so "bar"
is twice as likely to be returned as "foo"
.
Optional feature:
Add an overload to this new function that needs to be passed an iterator function to resolve each array items' weights; this is kinda how the Array.map()
and Array.reduce()
methods work:
const items = [ "foo", "bar", "baz" ];
function iterator(current, last, all)
{
// return the char code of the first letter of the string
// letters further down the alphabet have a higher weight (a = 1, z = 26)
const weight = (current.charCodeAt(0) - 96);
// Default to weight 1 if somehow the calculations above can produce NaN
if(isNaN(weight))
return 1;
return weight;
}
const result = scl.weightedRandom(items, iterator);
The iterator function gets called on each item and it should return a number
that's not NaN
(check with isNaN()
). Everything that is returned will be accumulated into the weights
array of the previous example and based on this a random item is selected and returned.