1 // given an array, will grab a weighted version of it
2 import { random } from 'lodash';
3 import { logger } from './logger';
5 export type Weighted = {
9 export function weighted<T>(options: T[], getWeight: (item: T) => number, weightPrecision: number = 100, defaultReturn?: T): T | undefined {
11 let segments: {start: number, end: number, item: T}[] = [];
13 options.forEach(option => {
14 const start = maxWeight;
15 maxWeight += (getWeight(option) * weightPrecision)
16 const end = maxWeight;
24 const selection = random(0, 100);
29 }, 'random weighted selection for item');
31 if(selection >= maxWeight) {
32 // there's a chance that the player actually gest nothing!
36 const found = segments.find(segment => {
37 return segment.start <= selection && segment.end >= selection;
40 return found ? found.item : defaultReturn;