Property Test Generator With Shrinking

Generate random inputs for a property test and shrink a failing case to a minimal counterexample.

TypescriptData Integrity

Code

typescriptsnippet
27 lines
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

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.