All files / src/math RandomDevice.ts

100% Statements 5/5
100% Branches 0/0
100% Functions 2/2
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                                          1x   8x                 8x 30x                             20x      
import { Fraction } from "./Fraction";
import { WithOdds } from "./WithOdds";
 
/**
 * A device generating random outcomes with specific odds. For example, a
 * classic 6-sided can be created with the following code:
 *
 * ```javascript
 * const d6 = new RandomDevice<number>([
 *   [1, new Fraction(1, 6)],
 *   [2, new Fraction(1, 6)],
 *   [3, new Fraction(1, 6)],
 *   [4, new Fraction(1, 6)],
 *   [5, new Fraction(1, 6)],
 *   [6, new Fraction(1, 6)]
 * ]);
 * ```
 *
 * @param Outcome
 *   The type of the outcome generated from this random device.
 */
export class RandomDevice<Outcome> {
  /** The sets and associated odds this random device generates. */
  private _outcomesWithOdds: WithOdds<Outcome[]>[] = [];
 
  /**
   * Constructor for a random device.
   *
   * @param {ReadonlyArray<[Outcome, Fraction]>} outcomesWithOdds
   *   An array of (outcome, odds) pairs.
   */
  constructor(outcomesWithOdds: ReadonlyArray<[Outcome, Fraction]>) {
    for (const elem of outcomesWithOdds) {
      this._outcomesWithOdds.push({
        oddsOfValue: elem[1],
        value: [elem[0]],
      });
    }
  }
 
  /**
   * Get the possible outcomes and odds for this random device.
   *
   * @returns {SetWithOdds<Outcome>[]}
   *   The possible outcomes (as sets) this random device can generate along
   * with the odds of each outcome.
   */
  public getOutcomesWithOdds(): WithOdds<Outcome[]>[] {
    return this._outcomesWithOdds;
  }
}