TS-Scribe - v1.2.0
    Preparing search index...

    Class WeightedList<T>

    A WeightedList can be used as an easy way to calculate probabilities based on weights, relative to other items inside the list.

    // Weighted random selection — higher weight = more likely
    const loot = new WeightedList<string>();
    loot.push(
    { data: 'Common Sword', weight: 70 },
    { data: 'Rare Shield', weight: 25 },
    { data: 'Legendary Bow', weight: 5 }
    );
    const drop = loot.random(); // 'Common Sword' ~70% of the time
    // Remove and return a random item (like drawing from a deck)
    const deck = new WeightedList<string>();
    deck.push({ data: 'Ace', weight: 1 }, { data: 'King', weight: 1 });
    const drawn = deck.popRandom(); // removes and returns one card
    // Check probabilities
    const list = new WeightedList<string>();
    list.push({ data: 'A', weight: 1 }, { data: 'B', weight: 3 });
    console.log(list.probability(0)); // 0.25 (A: 1/4 total weight)
    console.log(list.probability(1)); // 0.75 (B: 3/4 total weight)

    Type Parameters

    • T
    Index

    Accessors

    Constructors

    Methods

    • Returns the total weight of all items inside the list.

      Returns number

      The total weight of all items.

    • Returns and removes a random item from the list based on its weight.

      Returns InputEntry<T> | undefined

      The item and its weight, or undefined if the list is empty.

    • Returns the probability of a specific item inside the list based on its weight.

      Parameters

      • index: number

        The index of the item.

      Returns number | undefined

      The probability of the item, or undefined if the index is invalid.

    • Add one or more objects with their associated weights.

      Parameters

      • ...items: InputEntry<T>[]

        One or more objects with their weights to add to the list.

      Returns void

    • Get a random object from the list based on its weight. The higher the weight, the more likely it will be chosen.

      Returns T | undefined

      A random object from the list or undefined if the list is empty.

    • Returns a string representation of the WeightedList.

      Returns string

      A string summarizing the list, including length, total weight, and item details.

    • Returns all objects inside the list.

      Returns T[]

      An array of all objects in the list.

    • Returns a list of all objects and their associated weights.

      Returns InputEntry<T>[]

      An array of objects and their weights.