diff options
Diffstat (limited to 'pbt/ts/src/property.ts')
| -rw-r--r-- | pbt/ts/src/property.ts | 29 |
1 files changed, 17 insertions, 12 deletions
diff --git a/pbt/ts/src/property.ts b/pbt/ts/src/property.ts index 04f2a62..da05328 100644 --- a/pbt/ts/src/property.ts +++ b/pbt/ts/src/property.ts @@ -131,21 +131,26 @@ export function frequency<A>(distribution: [number, Gen<A>][]): Gen<A> { const total: number = distribution.reduce((acc, [freq, _]) => acc + freq, 0); return (rng: Prando) => (size: number) => { - const idx = rng.next(0, total); - let selectedGen: Option<Gen<A>> = none; - selectedGen = distribution.reduce((found, [freq, gen]) => { - if (isSome(found)) { - return found; - } else if (idx <= freq) { - return some(gen); - } else { - return none; - } - }, selectedGen); + const idx = Math.floor(rng.next(0, total)); + const [selectedGen, _] = distribution.reduce( + ([found, sum], [freq, gen]) => { + const current = sum + freq; + if (isSome(found)) { + return [found, current]; + } else if (idx <= current) { + return [some(gen), current]; + } else { + return [none, current]; + } + }, + [none as Option<Gen<A>>, 0], + ); const generator: Gen<A> = pipe( selectedGen, getOrElse((() => { - throw new Error(`invalid frequency distribution ${distribution}`); + throw new Error( + `invalid frequency distribution ${distribution}, idx=${idx}`, + ); }) as LazyArg<Gen<A>>), ); return generator(rng)(size); |
