AI 代码审查实战:用九个测试守住 Unicode Trie 多重集合的不变量
让 AI 写一棵前缀树,最容易得到的是二十六个字母槽位加一个布尔结束标记。它能通过插入 apple、查询 app 这样的演示,却没有回答真正影响上线的问题:同一个词来了三次怎么算,删掉其中一次会不会丢掉另外两次,删除短词是否误伤长词,失败的请求是否留下空节点。本文把审查对象收窄为一个明确的数据结构:以 Unicode 码点为边、支持重复词的多重集合 Trie。
审查的主线是状态守恒。每个节点保存 end、total 和 next:end 表示恰好在这里结束的词有多少份,total 表示这棵子树一共包含多少份词,next 保存下一条码点边。对任意节点,都必须满足 total 等于 end 加上所有直接子节点的 total。根节点对应空前缀,它的 total 就是整个集合的总份数;它的 end 专门存放空字符串的份数。

先写清楚可验收的接口契约
所有词与前缀只接受原始字符串;拒绝字符串包装对象,也不偷偷执行类型转换。输入必须是良构 UTF-16 字符串,单独的代理码元会被拒绝。每条边是一个 Unicode 标量值对应的字符串。
insert(word, n) 增加 n 份,返回这个词的新份数;deleteWord(word, n) 只有在数量足够时才扣除全部 n 份并返回 true,否则返回 false 且完全不变。省略 n 或传入 undefined 时默认一份,其他 n 必须是正的安全整数。
wordCount 返回精确词频;prefixCount 返回匹配前缀的总份数,不是不同词的个数。size 包含重复项。空字符串是合法的词,空前缀匹配所有词。
不做隐式大小写折叠、空白清理或 Unicode 规范化。entries 返回按码点数值字典序排列的独立结果数组,每个不同的词只出现一次,第二项是它的份数。
所有可达的非根节点都必须有正的 total;节点只能有一个父节点;外部代码不能取得内部 Map 或节点引用。错误参数与计数溢出在任何写入之前处理。
下面恰好九个例子,每个代码块都包含完整实现和自己的断言,复制成对应的 .mjs 文件即可单独运行,不依赖上一个例子。统一使用 node --unhandled-rejections=strict 文件名.mjs;该选项使未处理的 Promise 拒绝作为未捕获异常处理,但本文逻辑本身是同步的,正确性仍由断言负责。可核对 Node.js 命令行文档与 严格断言文档。
一、把查询成功提升为整棵树的守恒检查
先插入两份猫、一份猫咪和一份狗。猫节点同时是完整词的终点和猫咪的中间节点,所以它的 end 必须是二,而 total 必须是三。如果 AI 只设计一个 count,或者把经过节点当成词结束,两种查询就会被混为一谈。insert 返回的是词频,也不能误写成整个集合大小。
audit 会遍历全部可达节点,检查非负安全整数、节点没有重复归属、每条边只含一个合法码点,以及局部计数方程。输出中的 words 是不同词数,nodes 包含根节点。它是测试诊断入口,不参与查询的快速路径,也不会把可修改对象交给调用者。第一次审查就应该建立这个诊断能力,后面每个复杂操作才有可靠的落点。
独立文件:01-counts.mjs
import assert from 'node:assert/strict';
const node = () => ({ end: 0, total: 0, next: new Map() });
function tokens(value) {
if (typeof value !== 'string') throw new TypeError('string required');
const chars = [...value];
for (const ch of chars) {
const cp = ch.codePointAt(0);
if (cp >= 0xD800 && cp <= 0xDFFF) throw new RangeError('lone surrogate');
}
return chars;
}
function amount(n) {
if (!Number.isSafeInteger(n) || n <= 0) throw new RangeError('positive safe integer required');
}
class Trie {
#root = node();
#find(chars) {
let p = this.#root;
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return undefined;
}
return p;
}
get size() { return this.#root.total; }
wordCount(word) { return this.#find(tokens(word))?.end ?? 0; }
prefixCount(prefix) { return this.#find(tokens(prefix))?.total ?? 0; }
insert(word, n = 1) {
const chars = tokens(word);
amount(n);
if (n > Number.MAX_SAFE_INTEGER - this.size) throw new RangeError('overflow');
let p = this.#root;
p.total += n;
for (const ch of chars) {
if (!p.next.has(ch)) p.next.set(ch, node());
p = p.next.get(ch);
p.total += n;
}
p.end += n;
return p.end;
}
deleteWord(word, n = 1) {
const chars = tokens(word);
amount(n);
let p = this.#root;
const path = [p];
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return false;
path.push(p);
}
if (p.end < n) return false;
p.end -= n;
for (const q of path) q.total -= n;
for (let i = chars.length - 1; i >= 0; i--) {
if (path[i + 1].total !== 0) break;
path[i].next.delete(chars[i]);
}
return true;
}
entries(prefix = '') {
const start = this.#find(tokens(prefix));
if (!start) return [];
const out = [], stack = [[start, prefix]];
while (stack.length) {
const [p, word] = stack.pop();
if (p.end) out.push([word, p.end]);
const edges = [...p.next].sort((a, b) => a[0].codePointAt(0) - b[0].codePointAt(0));
for (let i = edges.length - 1; i >= 0; i--) stack.push([edges[i][1], word + edges[i][0]]);
}
return out;
}
audit() {
const seen = new Set(), stack = [this.#root];
let words = 0;
while (stack.length) {
const p = stack.pop();
assert.equal(seen.has(p), false);
seen.add(p);
assert(Number.isSafeInteger(p.end) && p.end >= 0);
assert(Number.isSafeInteger(p.total) && p.total >= 0);
let sum = p.end;
if (p.end) words++;
for (const [ch, q] of p.next) {
assert.equal(tokens(ch).length, 1);
assert(q.total > 0);
sum += q.total;
stack.push(q);
}
assert.equal(p.total, sum);
}
return { total: this.size, words, nodes: seen.size };
}
}
const t = new Trie();
assert.equal(t.insert('猫', 2), 2);
assert.equal(t.insert('猫咪'), 1);
assert.equal(t.insert('狗'), 1);
assert.equal(t.wordCount('猫'), 2);
assert.equal(t.prefixCount('猫'), 3);
assert.equal(t.wordCount('猫咪'), 1);
assert.equal(t.wordCount('不存在'), 0);
assert.equal(t.prefixCount('不存在'), 0);
console.log(JSON.stringify(t.entries()));
console.log(JSON.stringify(t.audit()));精确输出:
[["狗",1],["猫",2],["猫咪",1]]
{"total":4,"words":3,"nodes":4}二、按码点建边,并明确拒绝破碎代理项
JavaScript 字符串长度和下标使用 UTF-16 码元;字符串迭代器按码点产生字符串,具体规则见 ECMAScript 字符串迭代器规范。因此 😀A 的 length 是三,而展开后只有两个元素。使用 word[i] 或 split 空分隔符建边,会把补充平面字符拆成两条边,产生契约不允许的半个字符前缀。
这里还主动拒绝单独出现的高、低代理码元,避免把 JavaScript 可以保存的破碎序列当作合法输入。检查会扫描整个输入后才进入写入阶段。注意,码点不等于用户感知的一个字形:女程序员表情包含三个码点,查询其中第一个码点仍是合法前缀。若业务需要完整字素簇边界,那是另一套分词契约,不能只改页面文案。
独立文件:02-codepoints.mjs
import assert from 'node:assert/strict';
const node = () => ({ end: 0, total: 0, next: new Map() });
function tokens(value) {
if (typeof value !== 'string') throw new TypeError('string required');
const chars = [...value];
for (const ch of chars) {
const cp = ch.codePointAt(0);
if (cp >= 0xD800 && cp <= 0xDFFF) throw new RangeError('lone surrogate');
}
return chars;
}
function amount(n) {
if (!Number.isSafeInteger(n) || n <= 0) throw new RangeError('positive safe integer required');
}
class Trie {
#root = node();
#find(chars) {
let p = this.#root;
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return undefined;
}
return p;
}
get size() { return this.#root.total; }
wordCount(word) { return this.#find(tokens(word))?.end ?? 0; }
prefixCount(prefix) { return this.#find(tokens(prefix))?.total ?? 0; }
insert(word, n = 1) {
const chars = tokens(word);
amount(n);
if (n > Number.MAX_SAFE_INTEGER - this.size) throw new RangeError('overflow');
let p = this.#root;
p.total += n;
for (const ch of chars) {
if (!p.next.has(ch)) p.next.set(ch, node());
p = p.next.get(ch);
p.total += n;
}
p.end += n;
return p.end;
}
deleteWord(word, n = 1) {
const chars = tokens(word);
amount(n);
let p = this.#root;
const path = [p];
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return false;
path.push(p);
}
if (p.end < n) return false;
p.end -= n;
for (const q of path) q.total -= n;
for (let i = chars.length - 1; i >= 0; i--) {
if (path[i + 1].total !== 0) break;
path[i].next.delete(chars[i]);
}
return true;
}
entries(prefix = '') {
const start = this.#find(tokens(prefix));
if (!start) return [];
const out = [], stack = [[start, prefix]];
while (stack.length) {
const [p, word] = stack.pop();
if (p.end) out.push([word, p.end]);
const edges = [...p.next].sort((a, b) => a[0].codePointAt(0) - b[0].codePointAt(0));
for (let i = edges.length - 1; i >= 0; i--) stack.push([edges[i][1], word + edges[i][0]]);
}
return out;
}
audit() {
const seen = new Set(), stack = [this.#root];
let words = 0;
while (stack.length) {
const p = stack.pop();
assert.equal(seen.has(p), false);
seen.add(p);
assert(Number.isSafeInteger(p.end) && p.end >= 0);
assert(Number.isSafeInteger(p.total) && p.total >= 0);
let sum = p.end;
if (p.end) words++;
for (const [ch, q] of p.next) {
assert.equal(tokens(ch).length, 1);
assert(q.total > 0);
sum += q.total;
stack.push(q);
}
assert.equal(p.total, sum);
}
return { total: this.size, words, nodes: seen.size };
}
}
const t = new Trie();
t.insert('😀A', 2);
t.insert('👩💻');
assert.equal(t.prefixCount('😀'), 2);
assert.equal(t.wordCount('😀'), 0);
assert.equal(t.prefixCount('👩'), 1);
const before = t.entries();
assert.throws(() => t.insert('\uD83D'), RangeError);
assert.throws(() => t.prefixCount('\uD83D'), RangeError);
assert.deepEqual(t.entries(), before);
console.log(JSON.stringify({ units: '😀A'.length, points: [...'😀A'].length,
joinedEmojiPoints: [...'👩💻'].length }));
console.log(JSON.stringify(t.audit()));精确输出:
{"units":3,"points":2,"joinedEmojiPoints":3}
{"total":3,"words":2,"nodes":6}三、让空字符串自然落在根节点
空字符串往往被 AI 代码以一个早退条件吞掉,结果 size、空前缀和词枚举互相矛盾。本实现允许空字符串,因此它无需额外节点,根节点的 end 就是它的词频。插入两份空词、三份字、两份字典后,总份数是七,不同词只有三个;空前缀查询必须返回七。
删除一份空词时,路径数组只有根节点,修改它的 end 和 total 即可,剪枝循环不会进入。根节点始终存在,包括集合完全清空以后。这个设计使空词、普通词和共享前缀沿用同一条计数方程,减少分支特判。审查时应分别断言空词词频与空前缀总数,不能把两者都写成 size。
独立文件:03-empty.mjs
import assert from 'node:assert/strict';
const node = () => ({ end: 0, total: 0, next: new Map() });
function tokens(value) {
if (typeof value !== 'string') throw new TypeError('string required');
const chars = [...value];
for (const ch of chars) {
const cp = ch.codePointAt(0);
if (cp >= 0xD800 && cp <= 0xDFFF) throw new RangeError('lone surrogate');
}
return chars;
}
function amount(n) {
if (!Number.isSafeInteger(n) || n <= 0) throw new RangeError('positive safe integer required');
}
class Trie {
#root = node();
#find(chars) {
let p = this.#root;
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return undefined;
}
return p;
}
get size() { return this.#root.total; }
wordCount(word) { return this.#find(tokens(word))?.end ?? 0; }
prefixCount(prefix) { return this.#find(tokens(prefix))?.total ?? 0; }
insert(word, n = 1) {
const chars = tokens(word);
amount(n);
if (n > Number.MAX_SAFE_INTEGER - this.size) throw new RangeError('overflow');
let p = this.#root;
p.total += n;
for (const ch of chars) {
if (!p.next.has(ch)) p.next.set(ch, node());
p = p.next.get(ch);
p.total += n;
}
p.end += n;
return p.end;
}
deleteWord(word, n = 1) {
const chars = tokens(word);
amount(n);
let p = this.#root;
const path = [p];
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return false;
path.push(p);
}
if (p.end < n) return false;
p.end -= n;
for (const q of path) q.total -= n;
for (let i = chars.length - 1; i >= 0; i--) {
if (path[i + 1].total !== 0) break;
path[i].next.delete(chars[i]);
}
return true;
}
entries(prefix = '') {
const start = this.#find(tokens(prefix));
if (!start) return [];
const out = [], stack = [[start, prefix]];
while (stack.length) {
const [p, word] = stack.pop();
if (p.end) out.push([word, p.end]);
const edges = [...p.next].sort((a, b) => a[0].codePointAt(0) - b[0].codePointAt(0));
for (let i = edges.length - 1; i >= 0; i--) stack.push([edges[i][1], word + edges[i][0]]);
}
return out;
}
audit() {
const seen = new Set(), stack = [this.#root];
let words = 0;
while (stack.length) {
const p = stack.pop();
assert.equal(seen.has(p), false);
seen.add(p);
assert(Number.isSafeInteger(p.end) && p.end >= 0);
assert(Number.isSafeInteger(p.total) && p.total >= 0);
let sum = p.end;
if (p.end) words++;
for (const [ch, q] of p.next) {
assert.equal(tokens(ch).length, 1);
assert(q.total > 0);
sum += q.total;
stack.push(q);
}
assert.equal(p.total, sum);
}
return { total: this.size, words, nodes: seen.size };
}
}
const t = new Trie();
t.insert('', 2);
t.insert('字', 3);
t.insert('字典', 2);
assert.equal(t.size, 7);
assert.equal(t.prefixCount(''), 7);
assert.equal(t.wordCount(''), 2);
assert.equal(t.prefixCount('字'), 5);
assert.equal(t.deleteWord(''), true);
assert.equal(t.prefixCount(''), 6);
assert.equal(t.wordCount(''), 1);
console.log(JSON.stringify(t.entries()));
console.log(JSON.stringify(t.audit()));精确输出:
[["",1],["字",3],["字典",2]]
{"total":6,"words":3,"nodes":3}四、先证明能删,再扣减,最后反向剪枝
删除分为三个阶段:只读地找到完整路径并确认终点份数足够;一次扣减终点和路径上全部 total;从叶子向根删除 total 已归零的边。删除 car 不能直接移除 r 节点,因为 cart 仍经过那里。删除一个存在的前缀 ca 也不能成功,因为它根本不是已插入的完整词。
遇到第一条 total 仍为正的路径节点就可以停止向上剪枝。它的祖先既然仍包含这部分词,也不可能归零。剪枝依据是子树份数,不是 end 是否为零,更不能只判断子节点数。例子先检验超额删除不改变枚举,再检查最终只剩根节点;这样既能抓住内容错误,也能抓住长期运行才显现的空分支泄漏。
独立文件:04-delete-prune.mjs
import assert from 'node:assert/strict';
const node = () => ({ end: 0, total: 0, next: new Map() });
function tokens(value) {
if (typeof value !== 'string') throw new TypeError('string required');
const chars = [...value];
for (const ch of chars) {
const cp = ch.codePointAt(0);
if (cp >= 0xD800 && cp <= 0xDFFF) throw new RangeError('lone surrogate');
}
return chars;
}
function amount(n) {
if (!Number.isSafeInteger(n) || n <= 0) throw new RangeError('positive safe integer required');
}
class Trie {
#root = node();
#find(chars) {
let p = this.#root;
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return undefined;
}
return p;
}
get size() { return this.#root.total; }
wordCount(word) { return this.#find(tokens(word))?.end ?? 0; }
prefixCount(prefix) { return this.#find(tokens(prefix))?.total ?? 0; }
insert(word, n = 1) {
const chars = tokens(word);
amount(n);
if (n > Number.MAX_SAFE_INTEGER - this.size) throw new RangeError('overflow');
let p = this.#root;
p.total += n;
for (const ch of chars) {
if (!p.next.has(ch)) p.next.set(ch, node());
p = p.next.get(ch);
p.total += n;
}
p.end += n;
return p.end;
}
deleteWord(word, n = 1) {
const chars = tokens(word);
amount(n);
let p = this.#root;
const path = [p];
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return false;
path.push(p);
}
if (p.end < n) return false;
p.end -= n;
for (const q of path) q.total -= n;
for (let i = chars.length - 1; i >= 0; i--) {
if (path[i + 1].total !== 0) break;
path[i].next.delete(chars[i]);
}
return true;
}
entries(prefix = '') {
const start = this.#find(tokens(prefix));
if (!start) return [];
const out = [], stack = [[start, prefix]];
while (stack.length) {
const [p, word] = stack.pop();
if (p.end) out.push([word, p.end]);
const edges = [...p.next].sort((a, b) => a[0].codePointAt(0) - b[0].codePointAt(0));
for (let i = edges.length - 1; i >= 0; i--) stack.push([edges[i][1], word + edges[i][0]]);
}
return out;
}
audit() {
const seen = new Set(), stack = [this.#root];
let words = 0;
while (stack.length) {
const p = stack.pop();
assert.equal(seen.has(p), false);
seen.add(p);
assert(Number.isSafeInteger(p.end) && p.end >= 0);
assert(Number.isSafeInteger(p.total) && p.total >= 0);
let sum = p.end;
if (p.end) words++;
for (const [ch, q] of p.next) {
assert.equal(tokens(ch).length, 1);
assert(q.total > 0);
sum += q.total;
stack.push(q);
}
assert.equal(p.total, sum);
}
return { total: this.size, words, nodes: seen.size };
}
}
const t = new Trie();
t.insert('car', 2); t.insert('cart'); t.insert('cat');
assert.equal(t.deleteWord('car'), true);
assert.equal(t.prefixCount('ca'), 3);
const before = t.entries();
assert.equal(t.deleteWord('car', 2), false);
assert.equal(t.deleteWord('ca'), false);
assert.equal(t.deleteWord('absent'), false);
assert.deepEqual(t.entries(), before);
assert.equal(t.deleteWord('car'), true);
assert.equal(t.wordCount('cart'), 1);
assert.equal(t.prefixCount('car'), 1);
console.log(JSON.stringify(t.audit()));
assert.equal(t.deleteWord('cat'), true);
assert.equal(t.deleteWord('cart'), true);
console.log(JSON.stringify(t.audit()));精确输出:
{"total":2,"words":2,"nodes":6}
{"total":0,"words":0,"nodes":1}五、错误请求的原子性必须连拓扑一起检查
先创建节点再验证数量,是一种很隐蔽的错误:查询看似没变,节点数却持续增加。本实现先把整个词转换为合法码点数组,再验证 n,最后用总份数检查溢出。根 total 是所有计数的上界,因此只要根加 n 不超过最大安全整数,路径上其他计数加 n 也不会越界。用最大值减当前总数进行比较,能避开先相加造成的精度问题。
下面把零、负数、小数、非有限数、数字字符串和 BigInt 都列为无效数量;对不存在的词做无效删除也必须抛错,不能靠不存在提前返回来绕过参数契约。测试同时比较内容与节点统计,并用一个最大安全整数计数验证失败的插入没有新增分支。这里的原子性指这些可预期的输入失败,不承诺内存耗尽、进程终止或恶意篡改内建对象后的事务回滚。
独立文件:05-atomic.mjs
import assert from 'node:assert/strict';
const node = () => ({ end: 0, total: 0, next: new Map() });
function tokens(value) {
if (typeof value !== 'string') throw new TypeError('string required');
const chars = [...value];
for (const ch of chars) {
const cp = ch.codePointAt(0);
if (cp >= 0xD800 && cp <= 0xDFFF) throw new RangeError('lone surrogate');
}
return chars;
}
function amount(n) {
if (!Number.isSafeInteger(n) || n <= 0) throw new RangeError('positive safe integer required');
}
class Trie {
#root = node();
#find(chars) {
let p = this.#root;
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return undefined;
}
return p;
}
get size() { return this.#root.total; }
wordCount(word) { return this.#find(tokens(word))?.end ?? 0; }
prefixCount(prefix) { return this.#find(tokens(prefix))?.total ?? 0; }
insert(word, n = 1) {
const chars = tokens(word);
amount(n);
if (n > Number.MAX_SAFE_INTEGER - this.size) throw new RangeError('overflow');
let p = this.#root;
p.total += n;
for (const ch of chars) {
if (!p.next.has(ch)) p.next.set(ch, node());
p = p.next.get(ch);
p.total += n;
}
p.end += n;
return p.end;
}
deleteWord(word, n = 1) {
const chars = tokens(word);
amount(n);
let p = this.#root;
const path = [p];
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return false;
path.push(p);
}
if (p.end < n) return false;
p.end -= n;
for (const q of path) q.total -= n;
for (let i = chars.length - 1; i >= 0; i--) {
if (path[i + 1].total !== 0) break;
path[i].next.delete(chars[i]);
}
return true;
}
entries(prefix = '') {
const start = this.#find(tokens(prefix));
if (!start) return [];
const out = [], stack = [[start, prefix]];
while (stack.length) {
const [p, word] = stack.pop();
if (p.end) out.push([word, p.end]);
const edges = [...p.next].sort((a, b) => a[0].codePointAt(0) - b[0].codePointAt(0));
for (let i = edges.length - 1; i >= 0; i--) stack.push([edges[i][1], word + edges[i][0]]);
}
return out;
}
audit() {
const seen = new Set(), stack = [this.#root];
let words = 0;
while (stack.length) {
const p = stack.pop();
assert.equal(seen.has(p), false);
seen.add(p);
assert(Number.isSafeInteger(p.end) && p.end >= 0);
assert(Number.isSafeInteger(p.total) && p.total >= 0);
let sum = p.end;
if (p.end) words++;
for (const [ch, q] of p.next) {
assert.equal(tokens(ch).length, 1);
assert(q.total > 0);
sum += q.total;
stack.push(q);
}
assert.equal(p.total, sum);
}
return { total: this.size, words, nodes: seen.size };
}
}
const t = new Trie();
t.insert('safe', 2);
const before = { entries: t.entries(), stats: t.audit() };
const bad = [0, -1, 0.5, NaN, Infinity, '2', 1n, Number.MAX_SAFE_INTEGER + 1];
for (const n of bad) {
assert.throws(() => t.insert('safe-new', n), RangeError);
assert.throws(() => t.deleteWord('missing', n), RangeError);
}
for (const word of [null, 42, new String('safe')]) {
assert.throws(() => t.insert(word), TypeError);
assert.throws(() => t.deleteWord(word), TypeError);
}
assert.throws(() => t.insert('safe\uD800'), RangeError);
assert.deepEqual({ entries: t.entries(), stats: t.audit() }, before);
const large = new Trie();
large.insert('z', Number.MAX_SAFE_INTEGER);
assert.throws(() => large.insert('new'), RangeError);
assert.deepEqual(large.audit(), { total: Number.MAX_SAFE_INTEGER, words: 1, nodes: 2 });
assert.equal(large.deleteWord('z', Number.MAX_SAFE_INTEGER), true);
assert.deepEqual(large.audit(), { total: 0, words: 0, nodes: 1 });
console.log('invalid operations: unchanged');
console.log('overflow: unchanged; full delete: empty');精确输出:
invalid operations: unchanged overflow: unchanged; full delete: empty
六、规范化属于明确的键策略
外观相近的预组合字符与组合序列,进入树时可能走完全不同的路径。本文的默认策略是保留原始码点序列,所以 é 与 e 加组合重音符是两个键,也会产生不同的前缀统计。这是有意选择,不是 Unicode 支持不完整。ECMAScript normalize 规范提供 NFC 等形式,调用它是独立且显式的操作。
如果业务希望按 NFC 合并键,应在应用入口统一处理插入、删除和查询,并记录这条产品规则。例子展示同一批输入经 NFC 后合并,再通过相同的入口删除。尤其要小心前缀语义:规范化整个查询串后再查,未必保留原始字符串的每个前缀关系,例如 e 可以是组合序列的原始前缀,却不是其 NFC 结果的前缀。不要把规范化包装器描述成透明优化。
独立文件:06-normalization.mjs
import assert from 'node:assert/strict';
const node = () => ({ end: 0, total: 0, next: new Map() });
function tokens(value) {
if (typeof value !== 'string') throw new TypeError('string required');
const chars = [...value];
for (const ch of chars) {
const cp = ch.codePointAt(0);
if (cp >= 0xD800 && cp <= 0xDFFF) throw new RangeError('lone surrogate');
}
return chars;
}
function amount(n) {
if (!Number.isSafeInteger(n) || n <= 0) throw new RangeError('positive safe integer required');
}
class Trie {
#root = node();
#find(chars) {
let p = this.#root;
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return undefined;
}
return p;
}
get size() { return this.#root.total; }
wordCount(word) { return this.#find(tokens(word))?.end ?? 0; }
prefixCount(prefix) { return this.#find(tokens(prefix))?.total ?? 0; }
insert(word, n = 1) {
const chars = tokens(word);
amount(n);
if (n > Number.MAX_SAFE_INTEGER - this.size) throw new RangeError('overflow');
let p = this.#root;
p.total += n;
for (const ch of chars) {
if (!p.next.has(ch)) p.next.set(ch, node());
p = p.next.get(ch);
p.total += n;
}
p.end += n;
return p.end;
}
deleteWord(word, n = 1) {
const chars = tokens(word);
amount(n);
let p = this.#root;
const path = [p];
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return false;
path.push(p);
}
if (p.end < n) return false;
p.end -= n;
for (const q of path) q.total -= n;
for (let i = chars.length - 1; i >= 0; i--) {
if (path[i + 1].total !== 0) break;
path[i].next.delete(chars[i]);
}
return true;
}
entries(prefix = '') {
const start = this.#find(tokens(prefix));
if (!start) return [];
const out = [], stack = [[start, prefix]];
while (stack.length) {
const [p, word] = stack.pop();
if (p.end) out.push([word, p.end]);
const edges = [...p.next].sort((a, b) => a[0].codePointAt(0) - b[0].codePointAt(0));
for (let i = edges.length - 1; i >= 0; i--) stack.push([edges[i][1], word + edges[i][0]]);
}
return out;
}
audit() {
const seen = new Set(), stack = [this.#root];
let words = 0;
while (stack.length) {
const p = stack.pop();
assert.equal(seen.has(p), false);
seen.add(p);
assert(Number.isSafeInteger(p.end) && p.end >= 0);
assert(Number.isSafeInteger(p.total) && p.total >= 0);
let sum = p.end;
if (p.end) words++;
for (const [ch, q] of p.next) {
assert.equal(tokens(ch).length, 1);
assert(q.total > 0);
sum += q.total;
stack.push(q);
}
assert.equal(p.total, sum);
}
return { total: this.size, words, nodes: seen.size };
}
}
const raw = new Trie();
raw.insert('\u00E9');
raw.insert('e\u0301', 2);
assert.equal(raw.wordCount('\u00E9'), 1);
assert.equal(raw.wordCount('e\u0301'), 2);
assert.equal(raw.prefixCount('e'), 2);
assert.equal(raw.prefixCount('\u00E9'), 1);
const normalized = new Trie();
const key = s => s.normalize('NFC');
normalized.insert(key('\u00E9'));
normalized.insert(key('e\u0301'), 2);
assert.equal(normalized.wordCount(key('e\u0301')), 3);
assert.equal(normalized.deleteWord(key('e\u0301')), true);
assert.equal(normalized.wordCount(key('\u00E9')), 2);
console.log(JSON.stringify(raw.audit()));
console.log(JSON.stringify(normalized.audit()));精确输出:
{"total":3,"words":2,"nodes":4}
{"total":2,"words":1,"nodes":2}七、枚举顺序要能跨插入顺序复现
本节把排序契约写到可以直接断言的程度:按每个码点的数值依次比较,第一个不同码点较小的词在前;一个词是另一个词的前缀时,短词在前;空词最先输出。每个节点先输出自身终点,然后按已排序边进入子树。显式栈后进先出,因此压栈时必须逆序,否则遍历结果会恰好倒过来。
这不是中文拼音排序,也不是地区语言排序。默认数组字符串排序与所需的码点顺序也不一致,U+E000 和 U+10000 就能暴露区别。输出改用十六进制码点标识,避免私用区字符在不同字体上显示不清。entries 的前缀参数包含前缀自身的终点;不存在的前缀返回空数组。Map 只负责边的存取,不能把它的遍历顺序当作业务排序契约。
独立文件:07-enumeration.mjs
import assert from 'node:assert/strict';
const node = () => ({ end: 0, total: 0, next: new Map() });
function tokens(value) {
if (typeof value !== 'string') throw new TypeError('string required');
const chars = [...value];
for (const ch of chars) {
const cp = ch.codePointAt(0);
if (cp >= 0xD800 && cp <= 0xDFFF) throw new RangeError('lone surrogate');
}
return chars;
}
function amount(n) {
if (!Number.isSafeInteger(n) || n <= 0) throw new RangeError('positive safe integer required');
}
class Trie {
#root = node();
#find(chars) {
let p = this.#root;
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return undefined;
}
return p;
}
get size() { return this.#root.total; }
wordCount(word) { return this.#find(tokens(word))?.end ?? 0; }
prefixCount(prefix) { return this.#find(tokens(prefix))?.total ?? 0; }
insert(word, n = 1) {
const chars = tokens(word);
amount(n);
if (n > Number.MAX_SAFE_INTEGER - this.size) throw new RangeError('overflow');
let p = this.#root;
p.total += n;
for (const ch of chars) {
if (!p.next.has(ch)) p.next.set(ch, node());
p = p.next.get(ch);
p.total += n;
}
p.end += n;
return p.end;
}
deleteWord(word, n = 1) {
const chars = tokens(word);
amount(n);
let p = this.#root;
const path = [p];
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return false;
path.push(p);
}
if (p.end < n) return false;
p.end -= n;
for (const q of path) q.total -= n;
for (let i = chars.length - 1; i >= 0; i--) {
if (path[i + 1].total !== 0) break;
path[i].next.delete(chars[i]);
}
return true;
}
entries(prefix = '') {
const start = this.#find(tokens(prefix));
if (!start) return [];
const out = [], stack = [[start, prefix]];
while (stack.length) {
const [p, word] = stack.pop();
if (p.end) out.push([word, p.end]);
const edges = [...p.next].sort((a, b) => a[0].codePointAt(0) - b[0].codePointAt(0));
for (let i = edges.length - 1; i >= 0; i--) stack.push([edges[i][1], word + edges[i][0]]);
}
return out;
}
audit() {
const seen = new Set(), stack = [this.#root];
let words = 0;
while (stack.length) {
const p = stack.pop();
assert.equal(seen.has(p), false);
seen.add(p);
assert(Number.isSafeInteger(p.end) && p.end >= 0);
assert(Number.isSafeInteger(p.total) && p.total >= 0);
let sum = p.end;
if (p.end) words++;
for (const [ch, q] of p.next) {
assert.equal(tokens(ch).length, 1);
assert(q.total > 0);
sum += q.total;
stack.push(q);
}
assert.equal(p.total, sum);
}
return { total: this.size, words, nodes: seen.size };
}
}
const t = new Trie();
for (const word of ['😀', '\u{10000}', '\uE000', 'aa', 'a', '']) t.insert(word);
assert.deepEqual(t.entries().map(([w]) => w), ['', 'a', 'aa', '\uE000', '\u{10000}', '😀']);
assert.deepEqual(t.entries('a'), [['a', 1], ['aa', 1]]);
assert.deepEqual(t.entries('missing'), []);
assert.notDeepEqual(['\uE000', '\u{10000}'].sort(), ['\uE000', '\u{10000}']);
console.log(t.entries().map(([w, n]) =>
`${[...w].map(ch => ch.codePointAt(0).toString(16)).join('+') || 'empty'}:${n}`
).join(' '));
console.log(JSON.stringify(t.audit()));精确输出:
empty:1 61:1 61+61:1 e000:1 10000:1 1f600:1
{"total":6,"words":6,"nodes":6}八、私有节点和结果快照是两层边界
根节点使用类私有字段,每次实例化都创建自己的节点和 Map。entries 新建外层数组和每一个词频二元数组,只包含不可变的字符串与数字,因此调用者可以改坏自己的结果,却不能借此改写树。返回快照之后再次插入,旧数组也保持原来的内容。只复制外层数组、仍把内部可变对象放进结果,是代码审查中常见的伪隔离。
把普通属性 root 写成九百九十九不会触及真正的私有字段;只读 size 赋值与把方法借给普通对象都应失败。这里的封装是防止正常 API 使用中的别名泄漏,不是防御同进程所有恶意代码的安全沙箱。额外构造六千码点的长词,是为了验证查询、枚举、审计与删除都没有依赖递归调用栈;它不意味着输入长度无需限制。
独立文件:08-ownership.mjs
import assert from 'node:assert/strict';
const node = () => ({ end: 0, total: 0, next: new Map() });
function tokens(value) {
if (typeof value !== 'string') throw new TypeError('string required');
const chars = [...value];
for (const ch of chars) {
const cp = ch.codePointAt(0);
if (cp >= 0xD800 && cp <= 0xDFFF) throw new RangeError('lone surrogate');
}
return chars;
}
function amount(n) {
if (!Number.isSafeInteger(n) || n <= 0) throw new RangeError('positive safe integer required');
}
class Trie {
#root = node();
#find(chars) {
let p = this.#root;
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return undefined;
}
return p;
}
get size() { return this.#root.total; }
wordCount(word) { return this.#find(tokens(word))?.end ?? 0; }
prefixCount(prefix) { return this.#find(tokens(prefix))?.total ?? 0; }
insert(word, n = 1) {
const chars = tokens(word);
amount(n);
if (n > Number.MAX_SAFE_INTEGER - this.size) throw new RangeError('overflow');
let p = this.#root;
p.total += n;
for (const ch of chars) {
if (!p.next.has(ch)) p.next.set(ch, node());
p = p.next.get(ch);
p.total += n;
}
p.end += n;
return p.end;
}
deleteWord(word, n = 1) {
const chars = tokens(word);
amount(n);
let p = this.#root;
const path = [p];
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return false;
path.push(p);
}
if (p.end < n) return false;
p.end -= n;
for (const q of path) q.total -= n;
for (let i = chars.length - 1; i >= 0; i--) {
if (path[i + 1].total !== 0) break;
path[i].next.delete(chars[i]);
}
return true;
}
entries(prefix = '') {
const start = this.#find(tokens(prefix));
if (!start) return [];
const out = [], stack = [[start, prefix]];
while (stack.length) {
const [p, word] = stack.pop();
if (p.end) out.push([word, p.end]);
const edges = [...p.next].sort((a, b) => a[0].codePointAt(0) - b[0].codePointAt(0));
for (let i = edges.length - 1; i >= 0; i--) stack.push([edges[i][1], word + edges[i][0]]);
}
return out;
}
audit() {
const seen = new Set(), stack = [this.#root];
let words = 0;
while (stack.length) {
const p = stack.pop();
assert.equal(seen.has(p), false);
seen.add(p);
assert(Number.isSafeInteger(p.end) && p.end >= 0);
assert(Number.isSafeInteger(p.total) && p.total >= 0);
let sum = p.end;
if (p.end) words++;
for (const [ch, q] of p.next) {
assert.equal(tokens(ch).length, 1);
assert(q.total > 0);
sum += q.total;
stack.push(q);
}
assert.equal(p.total, sum);
}
return { total: this.size, words, nodes: seen.size };
}
}
const a = new Trie(), b = new Trie();
a.insert('shared', 2); b.insert('shared');
const snapshot = a.entries();
snapshot[0][0] = 'tampered'; snapshot[0][1] = 99;
snapshot.push(['fake', 100]);
a.root = { total: 999 };
assert.equal(a.size, 2);
assert.equal(a.wordCount('shared'), 2);
assert.equal(a.wordCount('fake'), 0);
assert.equal(b.wordCount('shared'), 1);
assert.throws(() => { a.size = 0; }, TypeError);
assert.throws(() => a.wordCount.call({}, 'shared'), TypeError);
const old = a.entries(); a.insert('later');
assert.deepEqual(old, [['shared', 2]]);
const deep = new Trie(), word = '界'.repeat(6000);
deep.insert(word);
assert.equal(deep.entries()[0][0], word);
assert.equal(deep.audit().nodes, 6001);
assert.equal(deep.deleteWord(word), true);
console.log('ownership: isolated; snapshot: detached');
console.log(JSON.stringify(deep.audit()));精确输出:
ownership: isolated; snapshot: detached
{"total":0,"words":0,"nodes":1}九、用简单 Map 模型反证复杂实现
单个故事容易碰巧通过,所以最后再维护一份只有完整词频的 Map。参考模型不保存节点、不维护前缀计数、不进行剪枝;每次查询都直接扫描所有词并按码点比较前缀。这种低效而直观的实现,与被测 Trie 的错误路径足够不同,比把同一段树算法复制一遍更有价值。参考排序也单独实现为完整词的数值序列比较。
固定种子的四百步操作会交错插入和删除,包含重复词、空词、补充平面字符、组合序列以及看起来像对象属性名的词。每一步都核对所有候选词频、若干前缀总量和有序枚举,再用所有存活词的不同码点前缀推导理论节点数。最后按模型一次删光全部词,确认树回到只有根的状态。固定种子有利于复现,但测试通过仍不等于数学证明,后续可以换种子、增加规模和业务词料。
独立文件:09-model.mjs
import assert from 'node:assert/strict';
const node = () => ({ end: 0, total: 0, next: new Map() });
function tokens(value) {
if (typeof value !== 'string') throw new TypeError('string required');
const chars = [...value];
for (const ch of chars) {
const cp = ch.codePointAt(0);
if (cp >= 0xD800 && cp <= 0xDFFF) throw new RangeError('lone surrogate');
}
return chars;
}
function amount(n) {
if (!Number.isSafeInteger(n) || n <= 0) throw new RangeError('positive safe integer required');
}
class Trie {
#root = node();
#find(chars) {
let p = this.#root;
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return undefined;
}
return p;
}
get size() { return this.#root.total; }
wordCount(word) { return this.#find(tokens(word))?.end ?? 0; }
prefixCount(prefix) { return this.#find(tokens(prefix))?.total ?? 0; }
insert(word, n = 1) {
const chars = tokens(word);
amount(n);
if (n > Number.MAX_SAFE_INTEGER - this.size) throw new RangeError('overflow');
let p = this.#root;
p.total += n;
for (const ch of chars) {
if (!p.next.has(ch)) p.next.set(ch, node());
p = p.next.get(ch);
p.total += n;
}
p.end += n;
return p.end;
}
deleteWord(word, n = 1) {
const chars = tokens(word);
amount(n);
let p = this.#root;
const path = [p];
for (const ch of chars) {
p = p.next.get(ch);
if (!p) return false;
path.push(p);
}
if (p.end < n) return false;
p.end -= n;
for (const q of path) q.total -= n;
for (let i = chars.length - 1; i >= 0; i--) {
if (path[i + 1].total !== 0) break;
path[i].next.delete(chars[i]);
}
return true;
}
entries(prefix = '') {
const start = this.#find(tokens(prefix));
if (!start) return [];
const out = [], stack = [[start, prefix]];
while (stack.length) {
const [p, word] = stack.pop();
if (p.end) out.push([word, p.end]);
const edges = [...p.next].sort((a, b) => a[0].codePointAt(0) - b[0].codePointAt(0));
for (let i = edges.length - 1; i >= 0; i--) stack.push([edges[i][1], word + edges[i][0]]);
}
return out;
}
audit() {
const seen = new Set(), stack = [this.#root];
let words = 0;
while (stack.length) {
const p = stack.pop();
assert.equal(seen.has(p), false);
seen.add(p);
assert(Number.isSafeInteger(p.end) && p.end >= 0);
assert(Number.isSafeInteger(p.total) && p.total >= 0);
let sum = p.end;
if (p.end) words++;
for (const [ch, q] of p.next) {
assert.equal(tokens(ch).length, 1);
assert(q.total > 0);
sum += q.total;
stack.push(q);
}
assert.equal(p.total, sum);
}
return { total: this.size, words, nodes: seen.size };
}
}
const t = new Trie(), model = new Map();
const words = ['', 'a', 'aa', 'ab', '字', '字典', '😀', '😀a',
'👩💻', 'e\u0301', '\u00E9', '\uE000', '\u{10000}', '__proto__'];
const prefixes = ['', 'a', '字', '😀', '👩', 'e', 'missing'];
const isPrefix = (word, prefix) => {
const a = [...word], b = [...prefix];
return b.length <= a.length && b.every((ch, i) => ch === a[i]);
};
function compare(a, b) {
const x = Array.from(a, c => c.codePointAt(0));
const y = Array.from(b, c => c.codePointAt(0));
for (let i = 0; i < Math.min(x.length, y.length); i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return x.length - y.length;
}
let seed = 0x5EED1234;
function random() {
seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5;
return seed >>> 0;
}
for (let step = 0; step < 400; step++) {
const word = words[random() % words.length], n = 1 + random() % 3;
const old = model.get(word) ?? 0;
if (random() % 2 === 0) {
model.set(word, old + n);
assert.equal(t.insert(word, n), old + n);
} else {
const expected = old >= n;
assert.equal(t.deleteWord(word, n), expected);
if (expected) {
if (old === n) model.delete(word); else model.set(word, old - n);
}
}
for (const word of words) assert.equal(t.wordCount(word), model.get(word) ?? 0);
for (const prefix of prefixes) {
const rows = [...model].filter(([w]) => isPrefix(w, prefix));
assert.equal(t.prefixCount(prefix), rows.reduce((n, [, count]) => n + count, 0));
rows.sort((a, b) => compare(a[0], b[0]));
assert.deepEqual(t.entries(prefix), rows);
}
const nodes = new Set(['']);
for (const word of model.keys()) {
let prefix = '';
for (const ch of word) { prefix += ch; nodes.add(prefix); }
}
assert.deepEqual(t.audit(), {
total: [...model.values()].reduce((a, b) => a + b, 0),
words: model.size, nodes: nodes.size
});
}
for (const [word, n] of model) assert.equal(t.deleteWord(word, n), true);
assert.deepEqual(t.entries(), []);
assert.deepEqual(t.audit(), { total: 0, words: 0, nodes: 1 });
console.log('model: 400 steps passed');
console.log('final drain: root only');精确输出:
model: 400 steps passed final drain: root only
复杂度、边界与给 AI 的复审要求
设输入有 L 个码点,插入、精确查询、前缀计数与删除沿路径执行 O(L) 次 Map 操作,词解析以及删除路径需要 O(L) 辅助空间。若采用常见的平均常数时间哈希访问模型,可以据此估算这些操作的平均时间;但 ECMAScript 对 Map 的要求是平均访问时间随元素数量次线性增长,并没有保证每次访问最坏 O(1)。不要把工程估算改写成语言规范保证。
枚举还要访问匹配子树的节点,并在每个节点排序它的出边;若出度为 d,比较排序通常还需 O(d log d) 的工作。当前教学实现每推进一条边都会拼接路径字符串,不能忽略字符串构造、输出总长度和显式栈的内存成本。audit 访问全部节点,并用集合检测共享节点,所以它适合测试或诊断,不应在每次生产查询后无条件运行。高流量服务还需要限制输入长度、键数量、枚举返回规模与单次请求成本。
把最终复审任务交给 AI 时,可以要求它逐项解释:为什么任何失败请求都没有写入,为什么根计数能约束全部后代,为什么删除短词保留长词,为什么零计数分支不可达,为什么空字符串不需要特殊存储,为什么枚举顺序不依赖插入历史,以及为什么返回值没有内部对象引用。如果某个回答只能说测试通过,却不能指向明确的状态变化与不变量,就继续追问反例。可靠的数据结构来自契约、状态方程与可执行证据相互校验。

