tests/sims/trie.test.ts
The automated tests for the /simulators/trie-autocomplete 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.
- Node count, word list, completions and the compressed (radix) tree match a word map.
// /simulators/trie-autocomplete
import { test } from 'node:test';
import { Trie, radix, radixCount, type RNode } from '../../src/lib/sims/trie.ts';
import { checker, lcg } from './check.ts';
test('node count, word list, completions and the compressed (radix) tree match a word map', () => {
const { ok, done } = checker();
const r = lcg(11);
const word = () => { const L = 1 + Math.floor(r() * 6); let w = ''; for (let i = 0; i < L; i++) w += 'abcde'[Math.floor(r() * 5)]; return w; };
for (let trial = 0; trial < 200; trial++) {
const t = new Trie();
const set = new Map<string, number>();
for (let i = 0; i < 40; i++) {
const w = word();
if (r() < 0.25 && set.size) {
const x = [...set.keys()][Math.floor(r() * set.size)];
ok(t.delete(x).removed, `delete ${x}`);
set.delete(x);
ok(!t.delete(x).removed, `second delete of ${x} succeeded`);
} else {
const f = 1 + Math.floor(r() * 9);
t.insert(w, f);
set.set(w, (set.get(w) ?? 0) + f);
}
const prefixes = new Set<string>();
for (const k of set.keys()) for (let j = 1; j <= k.length; j++) prefixes.add(k.slice(0, j));
ok(t.nodes().length === prefixes.size + 1, `${t.nodes().length} nodes, expected one per distinct prefix plus the root (${prefixes.size + 1})`);
ok(t.words().join() === [...set.keys()].sort().join(), 'word list');
const branchy = t.nodes().filter((n) => n.id !== 0 && (n.end || n.kids.size !== 1)).length;
ok(radixCount(radix(t)) === branchy + 1, 'radix tree node count');
const p = word().slice(0, 2);
const want = [...set.entries()].filter(([k]) => k.startsWith(p)).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 5).map(([k, f]) => k + f).join();
ok(t.complete(p, 5, 'freq').words.map((x) => x.word + x.freq).join() === want, `top completions for ${p}`);
for (const k of set.keys()) ok(t.has(k).found, `has ${k}`);
ok(!t.has(word() + 'zz').found, 'found a word never inserted');
}
const out: string[] = [];
const walk = (n: RNode, acc: string) => { if (n.end) out.push(acc + n.label); for (const k of n.kids) walk(k, acc + n.label); };
walk(radix(t), '');
ok(out.sort().join() === [...set.keys()].sort().join(), 'radix tree labels do not spell the words');
}
done();
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.