UNPKG

fast-check

Version:

Property based testing framework for JavaScript (like QuickCheck)

53 lines (52 loc) 2.2 kB
import { ArbitraryWithShrink } from './definition/ArbitraryWithShrink.js'; import { biasWrapper } from './definition/BiasedArbitraryWrapper.js'; import { Shrinkable } from './definition/Shrinkable.js'; import { biasNumeric } from './helpers/BiasNumeric.js'; import { shrinkNumber } from './helpers/ShrinkNumeric.js'; class IntegerArbitrary extends ArbitraryWithShrink { constructor(min, max) { super(); this.biasedIntegerArbitrary = null; this.min = min === undefined ? IntegerArbitrary.MIN_INT : min; this.max = max === undefined ? IntegerArbitrary.MAX_INT : max; } wrapper(value, shrunkOnce) { return new Shrinkable(value, () => this.shrink(value, shrunkOnce).map((v) => this.wrapper(v, true))); } generate(mrng) { return this.wrapper(mrng.nextInt(this.min, this.max), false); } shrink(value, shrunkOnce) { return shrinkNumber(this.min, this.max, value, shrunkOnce === true); } pureBiasedArbitrary() { if (this.biasedIntegerArbitrary != null) { return this.biasedIntegerArbitrary; } const log2 = (v) => Math.floor(Math.log(v) / Math.log(2)); this.biasedIntegerArbitrary = biasNumeric(this.min, this.max, IntegerArbitrary, log2); return this.biasedIntegerArbitrary; } withBias(freq) { return biasWrapper(freq, this, (originalArbitrary) => originalArbitrary.pureBiasedArbitrary()); } } IntegerArbitrary.MIN_INT = 0x80000000 | 0; IntegerArbitrary.MAX_INT = 0x7fffffff | 0; function integer(a, b) { if (a !== undefined && b !== undefined && a > b) throw new Error('fc.integer maximum value should be equal or greater than the minimum one'); return b === undefined ? new IntegerArbitrary(undefined, a) : new IntegerArbitrary(a, b); } function maxSafeInteger() { return integer(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); } function nat(a) { if (a !== undefined && a < 0) throw new Error('fc.nat value should be greater than or equal to 0'); return new IntegerArbitrary(0, a); } function maxSafeNat() { return nat(Number.MAX_SAFE_INTEGER); } export { integer, nat, maxSafeInteger, maxSafeNat };