A ROT.js compatible RNG interface

Hierarchy (view full)

Implements

Constructors

Properties

version: string = CURRENT_VERSION
version: string = CURRENT_VERSION

Methods

  • Internal source of uniformly distributed random numbers between 0 and 1, [0, 1)

    Simplest implementation would be Math.random()

    Returns number

  • Returns a Pool with the given entries based on this RNG.

    Pools allow you to draw (without replacement) from them.

    Type Parameters

    • T

    Parameters

    • Optionalentries: T[]

      An array of anything

    Returns Pool<T>

    const pool = rng.pool(['a', 'b', 'c', 'd']);

    pool.draw(); // 'b'
    pool.draw(); // 'c'
    pool.draw(); // 'a'
    pool.draw(); // 'd'
    pool.draw(); // PoolEmptyError('No more elements left to draw from in pool.')
  • Whether this is the same as another object interfacting RngInterface, i.e. they will generate the same next number.

    Parameters

    • other: any

      The thing to compare

    Returns boolean

Boolean Results

  • Results of an "n" in "chanceIn" chance of something happening.

    Parameters

    • n: number

      Numerator

    • chanceIn: number = 1

      Denominator

    Returns boolean

    Success or not

    A "1 in 10" chance would be:

    rng.chance(1, 10);
    
  • Results of an "from" to "to" chance of something happening.

    Parameters

    • from: number

      Left hand side

    • to: number

      Right hand side

    Returns boolean

    Success or not

    A "500 to 1" chance would be:

    rng.chanceTo(500, 1);
    

Choices

  • Takes a random choice from an array of values, with equal weight.

    Type Parameters

    • T

    Parameters

    • array: T[]

    Returns null | T

    The random choice from the array

  • Takes a random key from an object with a key:number pattern

    Using a Map allows objects to be specified as keys, can be useful for choosing between concrete objects.

    Parameters

    • data: any[] | Map<any, number> | Record<any, number>

      The values to choose from

    Returns any

    The random choice from the array

    Will return:

    • 'a' 1/10 of the time
    • 'b' 2/10 of the time
    • 'c' 3/10 of the time
    • 'd' 3/10 of the time
    rng.weightedChoice({
    a: 1,
    b: 2,
    c: 3,
    d: 4
    });

    Will return:

    • diamond 1/111 of the time
    • ruby 10/111 of the time
    • pebble 100/111 of the time
    const diamond = new Item('diamond');
    const ruby = new Item('ruby');
    const pebble = new Item('pebble');

    const choices = new Map();
    choices.set(diamond, 1);
    choices.set(ruby, 10);
    choices.set(pebble, 100);

    rng.weightedChoice(choices);

Distributions

  • A version of the bates distribution that returns gaussian normally distributed results, with n acting as a shape parameter.

    Parameters

    • n: number | {
          n?: number;
      } = 6

      Number of values to sum

    Returns number

    The mean of n uniform values

    NumberValidationError If the input parameters are not valid.

  • Probability that random number is less than p, returns 1 or 0.

    Support: {0, 1}

    Parameters

    • p: number | {
          p?: number;
      } = 0.5

    Returns number

    1 or 0, depending on if random number was less than p

    rng.bernoulli({ p: 0.5 });
    rng.bernoulli(0.5);

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Beta distribution.

    Support: (0, 1)

    Parameters

    • options: {
          alpha?: number;
          beta?: number;
      } = {}
      • Optionalalpha?: number

        The alpha parameter of the Beta distribution, must be positive, default 0.5.

      • Optionalbeta?: number

        The beta parameter of the Beta distribution, must be positive, default 0.5.

    Returns number

    A value from the Beta distribution, (0, 1).

    rng.beta({ alpha = 0.5, beta = 0.5 })
    rng.beta({ alpha = 1, beta = 2 })
    rng.beta({ beta = 1 })

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Beta-binomial distribution.

    Support: {0, 1, 2, ..., n}

    Parameters

    • options: {
          alpha?: number;
          beta?: number;
          n?: number;
      } = {}
      • Optionalalpha?: number

        The alpha parameter of the Beta distribution, default 1, must be positive.

      • Optionalbeta?: number

        The beta parameter of the Beta distribution, default 1, must be positive.

      • Optionaln?: number

        The number of trials, default 1, must be positive integer.

    Returns number

    The number of successes in n trials, {0, 1, 2, ..., n}

    rng.betaBinomial({ alpha = 1, beta = 2, n = 10 })
    rng.betaBinomial({ n = 100 })

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Binomial distribution.

    Probability distribution of getting number of successes of n trials of a boolean trial with probability p

    Support: {0, 1, 2, ..., n}

    Parameters

    • options: {
          n?: number;
          p?: number;
      } = {}
      • Optionaln?: number

        The number of trials, must be positive integer, default 1.

      • Optionalp?: number

        The probability of success, must be a number between 0 and 1 inclusive, default 0.5.

    Returns number

    The number of successes, {0, 1, 2, ..., n}.

    rng.binomial({ n = 1, p = 0.5 });
    rng.binomial({ n = 100, p = 0.1 });

    NumberValidationError If the input parameters are not valid.

  • Generates a Gaussian normal value via Box–Muller transform

    There are two ways of calling, either with an object with mean and stddev as keys, or just with two params, the mean and stddev

    Support: [0, 1]

    Parameters

    • mean: number | {
          mean?: number;
          stddev?: number;
      } = 0
    • stddev: number = 1

    Returns number

    A value from the Log-Normal distribution.

    rng.boxMuller({ mean: 0.5, stddev: 1 });
    rng.boxMuller(0.5, 1);

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Cauchy distribution.

    Support: (-∞, +∞)

    @example:

    rng.cauchy({ median: 2, scale: 1 }) rng.cauchy({ median: 2 }) rng.cauchy({ scale: 1 })

    Parameters

    • options: {
          median?: number;
          scale?: number;
      } = {}
      • Optionalmedian?: number

        The location parameter (median, sometimes called x0) - default 0.

      • Optionalscale?: number

        The scale parameter, must be positive - default 1.

    Returns number

    A value from the Cauchy distribution (-∞, +∞).

    NumberValidationError If the input parameters are not valid.

  • This function uses the inverse transform sampling method to generate an exponentially distributed random variable.

    Support: [0, ∞)

    Parameters

    • rate: number | {
          rate?: number;
      } = 1

    Returns number

    rng.exponential({ rate: 1 });
    rng.exponential(1);

    NumberValidationError If the input parameters are not valid.

  • Generates a random number from the Gamma distribution.

    Support: (0, ∞)

    Parameters

    • options: {
          rate?: number;
          scale?: number;
          shape?: number;
      } = {}
      • Optionalrate?: number

        The rate parameter, must be postive, default 1.

      • Optionalscale?: number

        The scale parameter, must be postive, ( = 1/rate).

      • Optionalshape?: number

        The shape parameter, must be postive, default 1.

    Returns number

    A random number from the Gamma distribution, from (0, ∞).

    rng.gamma({ shape = 0.5, rate = 0.5 })
    rng.gamma({ shape = 0.5, scale = 2 })
    rng.gamma({ shape = 0.5, rate = 0.5, scale = 2 }) // Redundant as scale = 1 / rate
    rng.gamma({ shape = 0.5, rate = 2, scale = 2 }) // Error('Cannot supply scale and rate')

    If both scale and rate are given and are not reciprocals of each other

    NumberValidationError If the input parameters are not valid.

  • Generates a gaussian normal number, but with a special skewing procedure that is sometimes useful.

    Parameters

    • options: {
          mean?: number;
          skew?: number;
          stddev?: number;
      } = {}
      • Optionalmean?: number
      • Optionalskew?: number
      • Optionalstddev?: number

        Must be > 0

    Returns number

    A normally distributed number

    rng.gaussian({ mean: 0.5, stddev: 0.5, skew: -1 });
    

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Hermite distribution.

    Support: {0, 1, 2, 3, ...}

    @example:

    rng.hermite({ lambda1: 1, lambda2: 2 }) rng.hermite({ lambda1: 1 }) rng.hermite({ lambda2: 2 })

    Parameters

    • options: {
          lambda1?: number;
          lambda2?: number;
      } = {}
      • Optionallambda1?: number

        The mean of the first Poisson process, must be positive.

      • Optionallambda2?: number

        The mean of the second Poisson process, must be positive.

    Returns number

    A value from the Hermite distribution, {0, 1, 2, 3, ...}

    NumberValidationError If the input parameters are not valid.

  • This function uses combinations to calculate probabilities for the hypergeometric distribution.

    The hypergeometric distribution is a discrete probability distribution that describes the probability of k successes (random draws for which the object drawn has a specified feature) in n draws, without replacement, from a finite population of size N that contains exactly K objects with that feature

    Support: {max(0, n+K-N), ..., min(n, K)}

    Parameters

    • options: {
          k?: number;
          K?: number;
          n?: number;
          N?: number;
      } = {}
      • Optionalk?: number

        The number of observed successes, must be positive integer lteq K and n.

      • OptionalK?: number

        The number of successes in the population, must be positive integer lteq N.

      • Optionaln?: number

        The number of draws, must be positive integer lteq N.

      • OptionalN?: number

        The population size, must be positive integer.

    Returns number

    The probability of exactly k successes in n draws, {max(0, n+K-N), ..., min(n, K)}.

    rng.hypergeometric({ N: 50, K: 10, n: 5 });
    rng.hypergeometric({ N: 50, K: 10, n: 5, k: 2 });

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Kumaraswamy distribution.

    Support: (0, 1)

    @example:

    rng.kumaraswamy({ alpha: 1, beta: 2 }) rng.kumaraswamy({ alpha: 1 }) rng.kumaraswamy({ beta: 2 })

    Parameters

    • options: {
          alpha?: number;
          beta?: number;
      } = {}
      • Optionalalpha?: number

        The first shape parameter of the Kumaraswamy distribution, must be positive.

      • Optionalbeta?: number

        The second shape parameter of the Kumaraswamy distribution, must be positive.

    Returns number

    A value from the Kumaraswamy distribution, (0, 1).

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Laplace distribution.

    Support: (-∞, +∞)

    @example:

    rng.laplace({ mean: 2, scale: 1 }) rng.laplace({ mean: 2 }) rng.laplace({ scale: 1 })

    Parameters

    • options: {
          mean?: number;
          scale?: number;
      } = {}
      • Optionalmean?: number

        The location parameter (mean) - default 0.

      • Optionalscale?: number

        The scale parameter, must be positive - default 1.

    Returns number

    A value from the Laplace distribution (-∞, +∞).

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Logistic distribution.

    Support: (-∞, +∞)

    @example:

    rng.logistic({ mean: 2, scale: 1 }) rng.logistic({ mean: 2 }) rng.logistic({ scale: 1 })

    Parameters

    • options: {
          mean?: number;
          scale?: number;
      } = {}
      • Optionalmean?: number

        The location parameter (mean) - default 0.

      • Optionalscale?: number

        The scale parameter, must be positive - default 1.

    Returns number

    A value from the Logistic distribution (-∞, +∞).

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Log-Normal distribution.

    Support: (0, ∞)

    @example:

    rng.logNormal({ mean: 2, stddev: 1 }) rng.logNormal({ mean: 2 }) rng.logNormal({ stddev: 1 })

    Parameters

    • options: {
          mean?: number;
          stddev?: number;
      } = {}
      • Optionalmean?: number

        The mean of the underlying normal distribution - default 0.

      • Optionalstddev?: number

        The standard deviation of the underlying normal distribution, must be positive - default 1.

    Returns number

    A value from the Log-Normal distribution (0, ∞).

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Generalized Pareto distribution.

    Support: [scale, ∞)

    Parameters

    • options: {
          location?: number;
          scale?: number;
          shape?: number;
      } = {}
      • Optionallocation?: number

        The location parameter, default 0.

      • Optionalscale?: number

        The scale parameter, must be positive ( > 0), default 1.

      • Optionalshape?: number

        The shape parameter, must be >= 0, default 0.5.

    Returns number

    A value from the Generalized Pareto distribution, [scale, ∞).

    rng.pareto({ shape: 0.5, scale: 1, location: 0 });
    rng.pareto({ location: 0 });
    rng.pareto({ scale: 1 });
    rng.pareto({ shape: 0.5 });

    NumberValidationError If the input parameters are not valid.

  • This function uses the fact that the Poisson distribution can be generated using a series of random numbers multiplied together until their product is less than e^(-lambda). The number of terms needed is the Poisson-distributed random variable.

    Support: {1, 2, 3 ...}

    Parameters

    • lambda: number | {
          lambda?: number;
      } = 1

    Returns number

    Poisson distributed random number, {1, 2, 3 ...}

    rng.poisson({ lambda: 1 });
    rng.poisson(1);

    NumberValidationError If the input parameters are not valid.

  • Generates a value from the Rayleigh distribution

    Support: [0, ∞)

    @example:

    rng.rayleigh({ scale: 2 }) rng.rayleigh(2) // Equivalent

    Parameters

    • scale: number | {
          scale?: number;
      } = 1

    Returns number

    A value from the Rayleigh distribution [0, ∞).

    NumberValidationError If the input parameter is not valid.

Random Number Generation

  • The chancy function has a very flexible calling pattern.

    You can pass it a dice string, an object or a number.

    • If passed a dice string, it will do a roll of that dice.
    • If passed a number, it will return that number
    • If passed a config object, it will return a randomly generated number based on that object

    The purpose of this is to have easily serialised random signatures that you can pass to a single function easily.

    All chancy distribution functions (that is, when called with ChancyInterface) can be called with min and max parameters, however, it's highly advised to tune your parameters someway else.

    Basically, the function will just keep resampling until a figure inside the range is generated. This can quickly lead to large recursion depths for out of bounds inputs, at which point an error is thrown.

    Type Parameters

    • T

    Parameters

    • input: T[]

      Chancy type input

    • Optionaldepth: number

    Returns T

    A randomly generated number or an element from a passed array

    rng.chancy(1); // returns 1
    rng.chancy('1d6'); // returns an int between 1 and 6 [1, 6]
    rng.chancy({ min: 10 }); // Equivalent to calling rng.random(10, Number.MAX_SAFE_INTEGER)
    rng.chancy({ max: 10 }); // Equivalent to calling rng.random(0, 10)
    rng.chancy({ min: 0, max: 1 }); // Equivalent to calling rng.random(0, 1)
    rng.chancy({ type: 'integer', min: 10 }); // Equivalent to calling rng.randInt(10, Number.MAX_SAFE_INTEGER)
    rng.chancy({ type: 'integer', max: 10 }); // Equivalent to calling rng.randInt(0, 10)
    rng.chancy({ type: 'integer', min: 10, max: 20 }); // Equivalent to calling rng.randInt(10, 20)
    rng.chancy({ type: 'normal', ...args }); // Equivalent to calling rng.normal(args)
    rng.chancy({ type: 'normal_integer', ...args }); // Equivalent to calling Math.floor(rng.normal(args))
    // You can call any of the 'distribution' type functions with chancy as well.
    rng.chancy({ type: 'boxMuller', ...args }); // Equivalent to calling rng.boxMuller(args)
    rng.chancy({ type: 'bates', ...args }); // Equivalent to calling rng.bates(args)
    rng.chancy({ type: 'exponential', ...args }); // Equivalent to calling rng.exponential(args)

    This is your monster file monster.json:

    {
    "id": "monster",
    "hp": {"min": 1, "max": 6, "type": "integer"},
    "attack": "1d4"
    }

    How about a stronger monster, with normally distributed health strong_monster.json:

    {
    "id": "strong_monster",
    "hp": {"min": 10, "max": 20, "type": "normal_integer"},
    "attack": "1d6+1"
    }

    Or something like this for boss_monster.json which has a fixed HP:

    {
    "id": "boss_monster",
    "hp": 140,
    "attack": "2d10+4"
    }

    Then in your code:

    import {Rng, Chancy} from GameRng;

    const rng = new Rng();

    class Monster {
    hp = 10;
    id;
    attack = '1d4';
    constructor ({id, hp = 10, attack} : {id: string, hp: Chancy, attack: Chancy} = {}) {
    this.id = options.id;
    this.hp = rng.chancy(hp);
    if (attack) this.attack = attack;
    }
    attack () {
    return rng.chancy(this.attack);
    }
    }

    const spec = await fetch('strong_monster.json').then(a => a.json());
    const monster = new Monster(spec);
  • The chancy function has a very flexible calling pattern.

    You can pass it a dice string, an object or a number.

    • If passed a dice string, it will do a roll of that dice.
    • If passed a number, it will return that number
    • If passed a config object, it will return a randomly generated number based on that object

    The purpose of this is to have easily serialised random signatures that you can pass to a single function easily.

    All chancy distribution functions (that is, when called with ChancyInterface) can be called with min and max parameters, however, it's highly advised to tune your parameters someway else.

    Basically, the function will just keep resampling until a figure inside the range is generated. This can quickly lead to large recursion depths for out of bounds inputs, at which point an error is thrown.

    Parameters

    Returns number

    A randomly generated number or an element from a passed array

    rng.chancy(1); // returns 1
    rng.chancy('1d6'); // returns an int between 1 and 6 [1, 6]
    rng.chancy({ min: 10 }); // Equivalent to calling rng.random(10, Number.MAX_SAFE_INTEGER)
    rng.chancy({ max: 10 }); // Equivalent to calling rng.random(0, 10)
    rng.chancy({ min: 0, max: 1 }); // Equivalent to calling rng.random(0, 1)
    rng.chancy({ type: 'integer', min: 10 }); // Equivalent to calling rng.randInt(10, Number.MAX_SAFE_INTEGER)
    rng.chancy({ type: 'integer', max: 10 }); // Equivalent to calling rng.randInt(0, 10)
    rng.chancy({ type: 'integer', min: 10, max: 20 }); // Equivalent to calling rng.randInt(10, 20)
    rng.chancy({ type: 'normal', ...args }); // Equivalent to calling rng.normal(args)
    rng.chancy({ type: 'normal_integer', ...args }); // Equivalent to calling Math.floor(rng.normal(args))
    // You can call any of the 'distribution' type functions with chancy as well.
    rng.chancy({ type: 'boxMuller', ...args }); // Equivalent to calling rng.boxMuller(args)
    rng.chancy({ type: 'bates', ...args }); // Equivalent to calling rng.bates(args)
    rng.chancy({ type: 'exponential', ...args }); // Equivalent to calling rng.exponential(args)

    This is your monster file monster.json:

    {
    "id": "monster",
    "hp": {"min": 1, "max": 6, "type": "integer"},
    "attack": "1d4"
    }

    How about a stronger monster, with normally distributed health strong_monster.json:

    {
    "id": "strong_monster",
    "hp": {"min": 10, "max": 20, "type": "normal_integer"},
    "attack": "1d6+1"
    }

    Or something like this for boss_monster.json which has a fixed HP:

    {
    "id": "boss_monster",
    "hp": 140,
    "attack": "2d10+4"
    }

    Then in your code:

    import {Rng, Chancy} from GameRng;

    const rng = new Rng();

    class Monster {
    hp = 10;
    id;
    attack = '1d4';
    constructor ({id, hp = 10, attack} : {id: string, hp: Chancy, attack: Chancy} = {}) {
    this.id = options.id;
    this.hp = rng.chancy(hp);
    if (attack) this.attack = attack;
    }
    attack () {
    return rng.chancy(this.attack);
    }
    }

    const spec = await fetch('strong_monster.json').then(a => a.json());
    const monster = new Monster(spec);
  • Rounds the results of a chancy call so that it's always an integer.

    Not quite equivalent to Math.round(rng.chancy(input)) because it will also transform {type: 'random'} to {type: 'integer'} which aren't quite the same.

    'random' has a range of [min, max) whereas interger is [min, max] (inclusive of max).

    Parameters

    Returns number

    chancy

  • Given a string dice representation, roll it

    Parameters

    • Optionaln:
          | string
          | number
          | number[]
          | Partial<DiceInterface>
    • Optionald: number
    • Optionalplus: number

    Returns number

    A random roll on the dice

    rng.dice('1d6');
    rng.dice('3d6+10');
    rng.dice('1d20-1');
    rng.dice('d10');

    Error if the given input is invalid.

  • Rolls dice and returns the results in an expanded format.

    Parameters

    • n:
          | string
          | number
          | number[]
          | Partial<DiceInterface> = 1
    • d: number = 6
    • plus: number = 0

    Returns {
        dice: number[];
        plus: number;
        total: number;
    }

    • dice: number[]
    • plus: number
    • total: number
    rng.diceExpanded('2d6+1'); // returns { dice: [3, 5], plus: 1, total: 9 }
    

    Error if the given input is invalid.

  • Generates a normally distributed number, but with a special clamping and skewing procedure that is sometimes useful.

    Note that the results of this aren't strictly gaussian normal when min/max are present, but for our puposes they should suffice.

    Otherwise, without min and max and skew, the results are gaussian normal.

    Parameters

    • Optionaloptions: {
          max?: number;
          mean?: number;
          min?: number;
          skew?: number;
          stddev?: number;
      } = {}
      • Optionalmax?: number

        Maximum value allowed for the output

      • Optionalmean?: number

        The mean value of the distribution

      • Optionalmin?: number

        Minimum value allowed for the output

      • Optionalskew?: number

        The skew to apply. -ve = left, +ve = right

      • Optionalstddev?: number

        Must be > 0 if present

    • Optionaldepth: number = 0

      used internally to track the recursion depth

    Returns number

    A normally distributed number

    rng.normal({ min: 0, max: 1, stddev: 0.1 });
    rng.normal({ mean: 0.5, stddev: 0.5 });

    NumberValidationError If the input parameters are not valid.

    MaxRecursionsError If the function recurses too many times in trying to generate in bounds numbers

  • Parameters

    • from: number | {
          from?: number;
          skew?: number;
          to?: number;
      } = 0
    • Optionalto: number
    • skew: number = 0

    Returns number

    A random number from [0, 1)

  • Parameters

    • from: number | {
          from?: number;
          skew?: number;
          to?: number;
      } = 0
    • to: number = 1
    • skew: number = 0

    Returns number

    A random integer from [0, 1]

  • Alias of randBetween

    Parameters

    • from: number | {
          from?: number;
          skew?: number;
          to?: number;
      } = 0
    • to: number = 1
    • skew: number = 0

    Returns number

Result Prediction

  • Determines the maximum value a Chancy input can take.

    Parameters

    Returns number

    Maximum value a call to chancy with these args can take

  • Determines the minimum value a Chancy input can take.

    Parameters

    Returns number

    Minimum value a call to chancy with these args can take

  • Gives the maximum result of a call to dice with these arguments

    Parameters

    • Optionaln:
          | string
          | number
          | number[]
          | Partial<DiceInterface>
    • Optionald: number
    • Optionalplus: number

    Returns number

  • Gives the minimum result of a call to dice with these arguments

    Parameters

    • Optionaln:
          | string
          | number
          | number[]
          | Partial<DiceInterface>
    • Optionald: number
    • Optionalplus: number

    Returns number

  • Determines the maximum value a Chancy input can take.

    Parameters

    Returns number

    Maximum value a call to chancy with these args can take

  • Determines the minimum value a Chancy input can take.

    Parameters

    Returns number

    Minimum value a call to chancy with these args can take

  • Gives the maximum result of a call to dice with these arguments

    Parameters

    • n:
          | string
          | number
          | number[]
          | Partial<DiceInterface> = 1
    • d: number = 6
    • plus: number = 0

    Returns number

  • Gives the minimum result of a call to dice with these arguments

    Parameters

    • n:
          | string
          | number
          | number[]
          | Partial<DiceInterface> = 1
    • d: number = 6
    • plus: number = 0

    Returns number

Seeding

  • Get the current seed.

    Note this may not be the same as the set seed if numbers have been generated since its inception. Also, strings are usually transformed to numbers.

    Returns number

    The current seed

  • Pass a function that will return uniform random numbers as the source of this rng's randomness.

    Supersedes and seed setting.

    Parameters

    Returns this

    const rng = new Rng();
    rng.randomSource(() => 1);

    assert(rng.random() === 1); // true
  • Seed the random number generator with the given seed.

    Parameters

    • Optionalseed: Seed

      Can be a string or a number

    Returns this

  • Create a new instance. Will use a globally set seed, so every instance returnd by this should generate the same numbers.

    Type Parameters

    • Rng

    Parameters

    Returns Rng

    An Rng instance, set to the given seed

Serialization

  • A serialized, storable version of this RNG that can be unserialized with unserialize

    Returns any

Utilities

  • Gets the bin "val" sits in when between "min" and "max" is separated by "bins" number of bins

    This is right aligning, so .5 rounds up

    This is useful when wanting only a discrete number values between two endpoints

    Parameters

    • val: number

      The value to bin

    • bins: number

      The number of bins

    • min: number

      Minimum value

    • max: number

      Maximum value

    Returns number

    The corresponding bin (left aligned)

    rng.bin(1.3, 11, 0, 10); // 1
    rng.bin(4.9, 11, 0, 10); // 5
    rng.bin(9.9, 11, 0, 10); // 10
    rng.bin(0.45, 11, 0, 10); // 0
    rng.bin(0.50, 11, 0, 10); // 1
  • Clamps a number to lower and upper bounds, inclusive

    Parameters

    • number: number
    • Optionallower: number
    • Optionalupper: number

    Returns number

    rng.clamp(5, 0, 1); // 1
    rng.clamp(-1, 0, 1); // 0
    rng.clamp(0.5, 0, 1); // 0.5
  • Returns a unique string of length len

    Parameters

    • len: number = 6

      Length of the string to generate

    Returns string

    A string of length "len"

  • Scales a number from [min, max] to [from, to].

    Some might call this linear interpolation.

    Min and max default to 0 and 1 respectively

    Parameters

    • number: number

      The number - must be 0 <= number <= 1

    • from: number

      The min number to scale to. When number === min, will return from

    • to: number

      The max number to scale to. When number === max, will return to

    • min: number = 0

      The minimum number can take, default 0

    • max: number = 1

      The maximum number can take, default 1

    Returns number

    A number scaled to the interval [from, to]

    rng.scale(0.5, 100, 200); // 150
    rng.scale(0, 100, 200); // 100
    rng.scale(1, 100, 200); // 200
    rng.scale(5, 100, 200, 0, 10); // 150
  • Scales a number from [0, 1] to [from, to].

    Some might call this linear interpolation

    Parameters

    • number: number

      The number - must be 0 <= number <= 1

    • from: number

      The min number to scale to. When number === 0, will return from

    • to: number

      The max number to scale to. When number === 1, will return to

    Returns number

    A normal number scaled to the interval [from, to]

    rng.scaleNorm(0.5, 100, 200); // 150
    rng.scaleNorm(0, 100, 200); // 100
    rng.scaleNorm(1, 100, 200); // 200
  • Returns a unique 14 character string.

    Highly collision resistant, and strictly incrementing

    Useful for using as object IDs or HTML ids (with prefix).

    Parameters

    • prefix: string = ''

      A prefix to include on the output

    Returns string

    a 14 character string

  • Given an array, gives a key:weight Map of entries in the array based on how many times they appear in the array.

    Parameters

    • data: any[]

      The values to choose from

    Returns Map<any, number>

    The weights of the array

    const weights = rng.weights(['a', 'b', 'c', 'a']);
    assert(weights['a'] === 2);
    assert(weights['b'] === 1);
    assert(weights['c'] === 1);