Skip to main content
The Deno 2 Release Candidate is here
Learn more
class WeightedRandomHelper
import { WeightedRandomHelper } from "https://deno.land/x/sptaki@1.2.0/helpers/WeightedRandomHelper.d.ts";

Methods

protected
commonDivisor(numbers: number[]): number
protected
gcd(a: number, b: number): number
deprecated
getWeightedInventoryItem(itemArray: { [tplId: string]: unknown; } | ArrayLike<unknown>): string
getWeightedValue<T>(itemArray: { [key: string]: unknown; } | ArrayLike<unknown>): T

Choos an item from the passed in array based on the weightings of each

reduceWeightValues(weightedDict: Record<string, number>): void

Find the greated common divisor of all weights and use it on the passed in dictionary

weightedRandom(items: any[], weights: any[]): { item: any; index: number; }

Picks the random item based on its weight. The items with higher weight will be picked more often (with a higher probability).

For example:

  • items = ['banana', 'orange', 'apple']
  • weights = [0, 0.2, 0.8]
  • weightedRandom(items, weights) in 80% of cases will return 'apple', in 20% of cases will return 'orange' and it will never return 'banana' (because probability of picking the banana is 0%)