Skip to content

Commit

Permalink
feat(boolean): add random boolean generator with optional bias
Browse files Browse the repository at this point in the history
  • Loading branch information
richrdkng committed Jul 16, 2023
1 parent 8cb4577 commit f926419
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
41 changes: 41 additions & 0 deletions packages/boolean/src/RandomBoolean/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { RandomEngine } from '@grandom/core'

export default class RandomBoolean {
private _engine: RandomEngine

constructor (engine: RandomEngine) {
this._engine = engine
}

/**
* A1
*/
boolean (): boolean

/**
* B1
*/
boolean (bias: number): boolean

boolean (arg1?: any): boolean {
if (typeof arg1 !== 'undefined') {
if (typeof arg1 !== 'number') {
throw new TypeError(`bias must be a number, got: ${typeof arg1}.`)
}

// NaN guard
if (arg1 === arg1) {
if (arg1 < 0) {
arg1 = 0
} else if (arg1 > 1) {
arg1 = 1
}

// return this._engine.nextDouble() < arg1
return this._engine.nextFloat() < arg1
}
}

return this._engine.nextBoolean()
}
}
9 changes: 6 additions & 3 deletions packages/boolean/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
export const boolean = (): number => {
import { BasicEngine } from '@grandom/engines'
import RandomBoolean from './RandomBoolean'

throw new Error('Unimplemented.')
}
const random = new RandomBoolean(new BasicEngine())
const boolean = random.boolean.bind(random)

export default boolean

0 comments on commit f926419

Please sign in to comment.