About: how pages are checked

tests/sims/avl.test.ts

The automated tests for the /simulators/balanced-tree simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.

  1. After each of 20,000 random inserts and deletes, every node is balanced, stored heights are right and the keys match a reference set.
// /simulators/balanced-tree: AVL insertion and deletion with rotations, checked after every change.
import { test } from 'node:test';
import { AVLTree, type ASnap } from '../../src/lib/sims/avl.ts';
import { checker, lcg } from './check.ts';

// Checked here from the snapshot, not with the model's checkAvl(): stored heights are right, every
// balance factor is -1, 0 or 1 and equals right height minus left height (or left minus right), and
// an in-order walk is sorted.
function avlProblems(t: ASnap): string[] {
	const out: string[] = [];
	const walk = (n: ASnap, lo: number, hi: number): number => {
		if (!n) return 0;
		if (n.key <= lo || n.key >= hi) out.push(`${n.key} out of order`);
		const hl = walk(n.l, lo, n.key), hr = walk(n.r, n.key, hi);
		if (Math.abs(hl - hr) > 1) out.push(`${n.key} unbalanced: ${hl} vs ${hr}`);
		if (n.h !== 1 + Math.max(hl, hr)) out.push(`${n.key} stores height ${n.h}, real ${1 + Math.max(hl, hr)}`);
		if (Math.abs(n.bf) !== Math.abs(hl - hr)) out.push(`${n.key} stores balance ${n.bf}, real ${hl - hr}`);
		return 1 + Math.max(hl, hr);
	};
	walk(t, -Infinity, Infinity);
	return out;
}
const keysOf = (t: ASnap): number[] => (t ? [...keysOf(t.l), t.key, ...keysOf(t.r)] : []);
const height = (t: ASnap): number => (t ? 1 + Math.max(height(t.l), height(t.r)) : 0);

test('after each of 20,000 random inserts and deletes, every node is balanced, stored heights are right and the keys match a reference set', () => {
	const { ok, done } = checker();
	const r = lcg(12);
	for (let run = 0; run < 40; run++) {
		const t = new AVLTree(), ref = new Set<number>();
		for (let i = 0; i < 500; i++) {
			const k = Math.floor(r() * 120);
			if (r() < 0.6) { t.insert(k); ref.add(k); } else { t.delete(k); ref.delete(k); }
			const s = t.snapshot();
			for (const p of avlProblems(s)) ok(false, `run ${run} step ${i}: ${p}`);
			ok(keysOf(s).join() === [...ref].sort((a, b) => a - b).join(), `run ${run} step ${i}: keys differ from the reference set`);
			ok(height(s) <= 1.4405 * Math.log2(ref.size + 2) - 0.3277 + 1e-9, `run ${run} step ${i}: height ${height(s)} over the AVL bound for n=${ref.size}`);
		}
	}
	done();
});

Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.

Published