Property Test Generator With Shrinking
Generate random inputs for a property test and shrink a failing case to a minimal counterexample.
Code
export interface PropertyCase { readonly numbers: number[]; }
export function check(numbers: number[]): boolean {
return numbers.every((n, i) => i === 0 || (numbers[i - 1] as number) <= n);
}
export function shrink(failing: number[], holds: (input: number[]) => boolean): number[] {
let current = failing;
let changed = true;
while (changed) {
changed = false;
for (let i = 0; i < current.length; i++) {
const candidate = current.filter((_, index) => index !== i);
if (!holds(candidate)) {
current = candidate;
changed = true;
break;
}
}
}
return current;
}
export function findCounterexample(seed: number[], holds: (input: number[]) => boolean): number[] | null {
if (!holds(seed)) return shrink(seed, holds);
return null;
}How the snippet works
The working surface is the functions check, shrink and findCounterexample — everything else is wiring.
The structure is a loop within a loop: while (changed) outside, for (let i = 0; i < current.length; i++) inside.
Applying it
The primary signature is export function check(numbers: number[])
The surface worth importing is check; the helpers around it are private to the snippet.
Statements that matter
return numbers.every((n, i) => i === 0 || (numbers[i - 1] as number) <= n);
export function findCounterexample(seed: number[], holds: (input: number[]) => boolean): number[] | null {
if (!holds(seed)) return shrink(seed, holds);
return null;
}
const candidate = current.filter((_, index) => index !== i);
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `check`, `shrink`, `findCounterexample` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.