Skip to content

Commit

Permalink
Frequency should be compatible with legacy node
Browse files Browse the repository at this point in the history
  • Loading branch information
dubzzz committed Mar 18, 2019
1 parent 2dc2cd0 commit 1af0b6f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
23 changes: 11 additions & 12 deletions src/check/arbitrary/FrequencyArbitrary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,20 @@ class FrequencyArbitrary<T> extends Arbitrary<T> {
readonly totalWeight: number;
constructor(readonly warbs: WeightedArbitrary<T>[]) {
super();
this.summedWarbs = warbs
.reduce(
(p: WeightedArbitrary<T>[], c) =>
p.concat({
weight: p[p.length - 1].weight + c.weight,
arbitrary: c.arbitrary
}),
[{ weight: 0, arbitrary: warbs[0].arbitrary }]
)
.slice(1);
this.totalWeight = this.summedWarbs[this.summedWarbs.length - 1].weight;
let currentWeight = 0;
this.summedWarbs = [];
for (let idx = 0; idx !== warbs.length; ++idx) {
currentWeight += warbs[idx].weight;
this.summedWarbs.push({ weight: currentWeight, arbitrary: warbs[idx].arbitrary });
}
this.totalWeight = currentWeight;
}
generate(mrng: Random): Shrinkable<T> {
const selected = mrng.nextInt(0, this.totalWeight - 1);
return this.summedWarbs.find(warb => selected < warb.weight)!.arbitrary.generate(mrng);
for (let idx = 0; idx !== this.summedWarbs.length; ++idx) {
if (selected < this.summedWarbs[idx].weight) return this.summedWarbs[idx].arbitrary.generate(mrng);
}
throw new Error(`Unable to generate from fc.frequency`);
}
withBias(freq: number) {
return new FrequencyArbitrary(this.warbs.map(v => ({ weight: v.weight, arbitrary: v.arbitrary.withBias(freq) })));
Expand Down
1 change: 1 addition & 0 deletions test/legacy/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,4 @@ testArbitrary(fc.json());
testArbitrary(fc.string());
testArbitrary(fc.fullUnicodeString());
testArbitrary(fc.lorem());
testArbitrary(fc.frequency({ weight: 1, arbitrary: fc.nat() }, { weight: 2, arbitrary: fc.double() }));

0 comments on commit 1af0b6f

Please sign in to comment.