-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(boolean): add random boolean generator with optional bias
- Loading branch information
Showing
2 changed files
with
47 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |