tests/sims/rbtree.test.ts
The automated tests for the /simulators/red-black-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.
- After each of 20,000 random inserts and deletes, the red-black rules hold and the keys match a reference set.
// /simulators/red-black-tree: CLRS red-black insertion and deletion, checked after every change.
import { test } from 'node:test';
import { RBTree, type Snap } from '../../src/lib/sims/rbtree.ts';
import { checker, lcg } from './check.ts';
// The red-black rules, checked here from the snapshot rather than with the model's own check():
// the root is black, no red node has a red child, every root-to-leaf path has the same number of
// black nodes, and an in-order walk is sorted.
function rbProblems(t: Snap): string[] {
const out: string[] = [];
if (t && t.c !== 'B') out.push('root is red');
const walk = (n: Snap, lo: number, hi: number): number => {
if (!n) return 1;
if (n.key <= lo || n.key >= hi) out.push(`${n.key} out of order`);
if (n.c === 'R' && ((n.l && n.l.c === 'R') || (n.r && n.r.c === 'R'))) out.push(`red ${n.key} has a red child`);
const a = walk(n.l, lo, n.key), b = walk(n.r, n.key, hi);
if (a !== b) out.push(`black heights ${a} and ${b} under ${n.key}`);
return a + (n.c === 'B' ? 1 : 0);
};
walk(t, -Infinity, Infinity);
return out;
}
const keysOf = (t: Snap): number[] => (t ? [...keysOf(t.l), t.key, ...keysOf(t.r)] : []);
const height = (t: Snap): number => (t ? 1 + Math.max(height(t.l), height(t.r)) : 0);
test('after each of 20,000 random inserts and deletes, the red-black rules hold and the keys match a reference set', () => {
const { ok, done } = checker();
const r = lcg(11);
for (let run = 0; run < 40; run++) {
const t = new RBTree(), 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 rbProblems(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) <= 2 * Math.log2(ref.size + 1) + 1e-9, `run ${run} step ${i}: height ${height(s)} over 2 log2(n+1) for n=${ref.size}`);
}
}
done();
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.