Class PTable<T>

A probability table is a set of items that have an assigned probability.

The goal of the probability table is to make it quick and easy to assign a set chance on multiple outcomes of a single event.

import {PTable} from "ptable";
const p = new PTable<string>();
p.add({value: "blah", weight: 1}); // add an entry for the string "blah" with a weight of 1
p.create("cake", 2); // shortcut for adding a string "cake" with a weight of 2
p.create("pie", 5);

for(let i=0;i<10000;i++){
const result = p.roll();
}
// ...

Type Parameters

  • T

Constructors

Properties

editMode: boolean = false
entries: PTableEntry<T>[] = []
totalWeight: number = 0

Methods

  • Add a series of entries to the PTable.

    After adding all entries, the probability ranges will be re-intialized for all entries based on the change in the total weight of all entries added.

    When adding lots of entries, you may want to look into PTable#populate.

    Parameters

    • Rest...entries: PrePTableEntry<T>[]

      The set of precursor PTable entries to add.

    Returns void

  • Create a new PTable entry.

    Parameters

    • value: T

      The value of the entry.

    • weight: number

      The weight of the entry.

    Returns void

  • Re-calculates the ranges of all entries based on their weights.

    Called every time a new entry is added, unless edit mode is enabled.

    Returns void

  • Enables edit mode, which disables re-initializing entry ranges with every addition.

    Edit mode is only enabled during the call of the provided callback function, which is executed immediately.

    After the callback function ends, edit mode is disabled.

    Parameters

    • edit: (() => void)

      A function called during edit mode.

        • (): void
        • Returns void

    Returns void

  • Accepts a P value between 0 and 1 that corresponds to the range of an entry in the PTable.

    If the p value falls within the range of the entry, its value will be returned.

    Parameters

    • p: number

      A value between 0 and 1.

    Returns T

    The value of the chosen entry.

    Attempting to roll an empty PTable.

    Failed to return a result. This generally means the provided P value is not within the range of any entries.

  • Generate a random number to use to pick an entry from the table.

    Returns T

    The rolled entry's value.

    Attempting to roll an empty PTable.

    Failed to return a result. This generally means the provided P value is not within the range of any entries.