UNPKG

fast-check

Version:

Property based testing framework for JavaScript (like QuickCheck)

33 lines (32 loc) 1.22 kB
import { Arbitrary } from './definition/Arbitrary.js'; class FrequencyArbitrary extends Arbitrary { constructor(warbs) { super(); this.warbs = warbs; 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) { const selected = mrng.nextInt(0, this.totalWeight - 1); 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) { return new FrequencyArbitrary(this.warbs.map((v) => ({ weight: v.weight, arbitrary: v.arbitrary.withBias(freq) }))); } } function frequency(...warbs) { if (warbs.length === 0) { throw new Error('fc.frequency expects at least one parameter'); } return new FrequencyArbitrary([...warbs]); } export { frequency };