All files / util rng.ts

100% Statements 15/15
50% Branches 1/2
100% Functions 4/4
100% Lines 12/12

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              17x 17x             40x 40x 40x             589x 589x 589x             123x 123x 123x 123x      
import prand from 'pure-rand'
 
export default class RNG {
  private generator: prand.RandomGenerator
  public seed: number
 
  constructor(seed?: number) {
    this.seed = seed ?? Date.now() ^ (Math.random() * 0x100000000)
    this.generator = prand.xoroshiro128plus(seed)
  }
 
  /**
   * Returns a uniformly distributed random integer between min and max
   */
  public uniformInt(min: number, max: number): number {
    const [value, rng] = prand.uniformIntDistribution(min, max)(this.generator)
    this.generator = rng
    return value
  }
 
  /*
  * Returns a uniformly distributed random float between min and max
  */
  public uniformFloat(min: number, max: number) {
    const [value, rng] = prand.uniformIntDistribution(min * 1000, max * 1000)(this.generator)
    this.generator = rng
    return value / 1000
  }
 
  /**
   * Returns a normally distributed random number with mean mu and standard deviation sigma.
   */
  public normalFloat(mu: number, sigma: number): number {
    let u = 0, v = 0
    while (u === 0) u = 1 - this.uniformFloat(0, 1)
    while (v === 0) v = this.uniformFloat(0, 1)
    return sigma * Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v) + mu
  }
}