AI 代码审查实战:JavaScript Robin Hood 哈希表的探测边界、回移删除与扩容证据
让 AI 写一个开放寻址哈希表,最容易得到的答案是:算出下标,发生冲突就向后找。代码看起来很短,真正危险的部分却藏在删除以后、数组绕回开头以后,以及第四个键触发扩容的那一刻。本文把 Robin Hood 哈希表当作一份需要验收的代码变更:先写清字符串键契约,再逐项检查探测、交换、删除与重建,最后让原生 Map 和独立结构断言共同提供证据。
这里的实现是可审查的教学容器,只支持明确列出的接口。我们不把它当成原生 Map 的替代品,也不据此推断 JavaScript 引擎内部采用哪种哈希表。九段程序都能单独保存为 .cjs 文件运行;本文实测环境为 Node.js 24.19.0,命令使用 node --use-strict --unhandled-rejections=strict 文件名.cjs。后两段为了可独立复制,完整保留了容器定义。

一、先封住隐式转换:键只接受原始字符串
审查的第一问是“哪些值能成为键”。本例只接受 typeof key 等于 "string" 的原始字符串,拒绝数字、对象、Symbol、null 和字符串包装对象。所有按键操作使用同一条规则;不会为了方便调用 String(key)。否则数字 1 与字符串 "1" 会意外合并,对象的 toString 还可能执行用户代码,让一次查找带来额外副作用。
字符串按照 JavaScript 的 UTF-16 码元序列比较,不做大小写折叠、Unicode 规范化或空白清理。因此空串、"__proto__"、包含单独代理码元的字符串都能成为键;外观相近的 "é" 与 "e\u0301" 是两个键。数据放在数组槽位记录中,键不会被当作普通对象的属性名,这也避免了把特殊属性名误当成原型操作。
默认散列采用 FNV 风格的逐码元混合:charCodeAt 读取一个码元,Math.imul 完成三十二位乘法,最后转成无符号整数。它不是对 UTF-8 字节计算的标准 FNV 编码,也没有密码学用途。关于码元和乘法的语言语义,依据 ECMAScript 的 charCodeAt 定义及 Math.imul 定义。散列相同不代表键相同,后面的查找仍然比较完整字符串。
示例 01,独立运行输出如下。
"use strict";
const assert = require("node:assert/strict");
function stringHash(key) {
if (typeof key !== "string") throw new TypeError("string key required");
let h = 2166136261;
for (let i = 0; i < key.length; i++) {
h = Math.imul(h ^ key.charCodeAt(i), 16777619) >>> 0;
}
return h;
}
assert.equal(stringHash(""), 2166136261);
assert.equal(stringHash("a"), 3826002220);
for (const bad of [1, null, undefined, {}, new String("a")]) {
assert.throws(() => stringHash(bad), TypeError);
}
const keys = ["", "__proto__", "e\u0301", "é", "\ud800", "😀"];
assert.notEqual(keys[2], keys[3]);
assert.equal(new Map(keys.map(k => [k, 1])).size, 6);
console.log("string contract: 6 distinct keys; invalid keys rejected");string contract: 6 distinct keys; invalid keys rejected
二、先保留一个反例:直接清空会切断查找路径
下面这段程序故意实现错误删除。A 与 B 的初始槽位都是一,B 因冲突存到了二。删除 A 时直接把槽一改为 null,查找 B 遇到这个空槽就返回不存在,尽管 B 还留在数组里。这个失败不需要大规模随机数据,两个键就能证明。
空槽在开放寻址表中带有语义:沿一条有效探测路径遇到它,可以停止查找。若删除随意制造空洞,这个证据便失效。另一类实现会引入墓碑标记并重新制定查找、插入、重建规则;本文选择后移元素来补洞,不混用两套删除语义。代码里的 null 只表示真正空槽,存储值本身仍然可以是 null 或 undefined。
示例 02,独立运行输出如下。
"use strict";
const assert = require("node:assert/strict");
const slots = [null, { key: "A" }, { key: "B" }, null];
function naiveHas(key) {
let i = 1; // A and B both start here.
for (let n = 0; n < slots.length; n++, i = (i + 1) % slots.length) {
if (slots[i] === null) return false;
if (slots[i].key === key) return true;
}
return false;
}
assert.equal(naiveHas("B"), true);
slots[1] = null; // Deliberately wrong deletion.
assert.equal(naiveHas("B"), false);
assert.equal(slots[2].key, "B");
console.log("counterexample: B remains stored but lookup returns false");counterexample: B remains stored but lookup returns false
三、Robin Hood 交换的是记录,也必须交换距离
给定容量 m,记录的初始槽位 home 为 hash 与 m−1 的按位与;实际槽位 i 对应的距离 d 为沿环向前走的步数。容量限制为二的幂,而且远小于三十二位下标边界,因而这里的位掩码计算有明确适用范围。d 是距离,不是一次操作累计访问了多少槽;读取初始槽时,d 为零,但已经进行了一次探测。
插入时,如果新到记录走得比当前记录更远,就让新记录占据当前位置,再带着被换出的记录继续前进。这是 NIST 对 Robin Hood 碰撞规则的定义所描述的核心动作。本例在距离相等时不交换;决定交换的是严格小于,而非小于等于。
审查交换语句之后,紧接着看 d++ 加给了谁。交换发生后,手里的变量已经指向被挤出的旧记录,它从自己的原距离再走一步,不能沿用新来记录的距离。下面的 place 是小型算法实验,前置条件是目标数组容量合法、键尚不存在且至少有一个空槽;完整接口会在插入前先处理重复键与容量。独立计数器 n 限制槽位访问次数,不能拿会随交换改变的 d 充当整个循环的终止计数器。
示例 03,独立运行输出如下。
"use strict";
const assert = require("node:assert/strict");
function place(a, input) {
const mask = a.length - 1;
let e = { ...input, d: 0 }, i = e.hash & mask;
for (let n = 0; n < a.length; n++, i = (i + 1) & mask) {
if (a[i] === null) { a[i] = e; return; }
if (a[i].d < e.d) [a[i], e] = [e, a[i]];
e.d++;
}
throw new Error("no empty slot");
}
const a = Array(8).fill(null);
for (const [key, hash] of [["A", 0], ["B", 1], ["C", 0]]) {
place(a, { key, hash });
}
assert.deepEqual(a.slice(0, 3).map(e => [e.key, e.d]),
[["A", 0], ["C", 1], ["B", 1]]);
console.log(a.filter(Boolean).map(e => `${e.key}:${e.d}`).join(" "));A:0 C:1 B:1
四、查找能提前停止,但距离并非全局有序
查找从目标键的 home 出发,每走一格就增加本次查找的距离。遇到空槽可以返回不存在;遇到某条记录的 d 小于本次距离,也可以提前返回不存在。原因不是“整段数组的距离单调递增”,而是更具体的路径条件:对于一个已经存入的键,从它的 home 到当前位置经过的每个槽都必须非空,而且槽内记录的距离不能小于这次查找走到该处的距离。
插入时的交换维护这条路径条件,后面正确的回移删除也会保留它。如果目标键真在更远处,它的查找路径便不应出现上述违例,所以遇到较小距离就已经获得了不存在的证据。反过来,距离相等还不能结束,下一格仍可能放着目标键。
下面的合法布局直接给出距离序列零、一、零。C 恰好位于自己的 home,距离重新降为零;它不会妨碍从 home 为二的位置查找 C,却能让寻找 home 为零的缺失键 X 停下来。这是审阅 AI 解释时很有用的反例:解释如果声称整个聚簇的 d 必须单调,就应当修改论证,而不是修改数据去迎合解释。所有查找仍然设有最多 m 次访问的硬边界,防止代码缺陷把同步调用变成无限循环。
示例 04,独立运行输出如下。
"use strict";
const assert = require("node:assert/strict");
const a = [
{ key: "A", hash: 0, d: 0 },
{ key: "B", hash: 0, d: 1 },
{ key: "C", hash: 2, d: 0 },
null
];
function find(key, hash) {
const mask = a.length - 1;
let i = hash & mask;
for (let d = 0; d < a.length; d++, i = (i + 1) & mask) {
const e = a[i];
if (e === null || e.d < d) return { index: -1, probes: d + 1 };
if (e.hash === hash && e.key === key) return { index: i, probes: d + 1 };
}
return { index: -1, probes: a.length };
}
assert.deepEqual(find("B", 0), { index: 1, probes: 2 });
assert.deepEqual(find("X", 0), { index: -1, probes: 3 });
assert.equal(find("C", 2).index, 2);
console.log("distances: 0,1,0; missing X stops after 3 probes");distances: 0,1,0; missing X stops after 3 probes
五、回移删除:空槽和距离零都是边界
删除命中后,当前位置成为待填补的洞。查看环上的下一个槽:若它非空且 d 大于零,就把该记录搬到洞里,并把 d 减一;洞随之移动到被搬空的位置。继续这个过程,直到下一格为空或者下一条记录的 d 已经为零,最后把当前洞标为 null。
为什么遇到距离零要停?这条记录已经在自己的 home,再往前搬一格就越过了它的起点,破坏查找路径。为什么每搬一次都要减一?位置向 home 靠近一步,距离必须同步变化;仅移动键值而不更新距离,会让提前结束的判断使用旧证据。Tessil/robin-map 的项目说明也明确采用线性 Robin Hood 探测与 backward shift deletion;本文代码为便于审查重新编写,并非该 C++ 实现的逐行翻译。
这个测试把连续记录放在六、七、零号槽,迫使删除穿过数组尾端;一号槽的 D 距离为零,应留在原地。循环内会短暂存在同一记录的两个引用,但过程没有用户回调,最终洞会被清掉。完整实现将数组保存在私有字段里,外部不能在移动中途观察或改写槽位。命中删除只减少一次 size,删除缺失键则返回 false 并保持原状态。
示例 05,独立运行输出如下。
"use strict";
const assert = require("node:assert/strict");
function eraseAt(a, hole) {
const mask = a.length - 1;
for (let n = 0; n < a.length; n++) {
const next = (hole + 1) & mask, e = a[next];
if (e === null || e.d === 0) { a[hole] = null; return; }
a[hole] = e;
e.d--;
hole = next;
}
throw new Error("deletion did not stop");
}
const a = Array(8).fill(null);
a[6] = { key: "A", d: 0 };
a[7] = { key: "B", d: 1 };
a[0] = { key: "C", d: 2 };
a[1] = { key: "D", d: 0 };
eraseAt(a, 6);
assert.deepEqual([a[6], a[7], a[0], a[1]], [
{ key: "B", d: 0 }, { key: "C", d: 1 }, null, { key: "D", d: 0 }
]);
console.log("wrap shift: B@6/0 C@7/1; D@1/0 stays put");wrap shift: B@6/0 C@7/1; D@1/0 stays put
六、扩容必须重建 home,旧距离不能照搬
扩容最常见的错误是把旧数组复制到更长数组,再沿用原来的下标和 d。容量从四变为八以后,掩码从三变为七;同一个完整散列值可能得到不同的 home。记录必须以新容量重新插入,距离从零重新计算。数组长度变了,不等于探测路径已经变得合法。
下面先建立旧表,再用缓存的完整散列值重建新表。重建时 place 为每个输入创建新记录,因此更新新表里的距离不会污染旧表。测试既检查每条记录的新距离,也确认旧数组完全没有变化。缓存的是完整 uint32 散列值,不能只缓存旧 home,否则下一次扩容已经缺少计算新位置所需的信息。
在完整 set 中,新增键将使占用超过四分之三时才扩容;更新已有键只改值,不增加 size,也不触发扩容。扩容先构造临时数组,把全部旧记录和本次新增记录都放进去,再发布新的数组引用。达到配置上限时先抛出 RangeError,原表不变。这个提交顺序说明的是正常同步异常下的状态保护,不承诺进程被终止或运行时内存耗尽以后仍能继续服务。
示例 06,独立运行输出如下。
"use strict";
const assert = require("node:assert/strict");
function place(a, input) {
const mask = a.length - 1;
let e = { ...input, d: 0 }, i = e.hash & mask;
for (let n = 0; n < a.length; n++, i = (i + 1) & mask) {
if (a[i] === null) { a[i] = e; return; }
if (a[i].d < e.d) [a[i], e] = [e, a[i]];
e.d++;
}
throw new Error("no empty slot");
}
const old = Array(4).fill(null);
for (const [key, hash] of [["A", 3], ["B", 7], ["C", 11]]) {
place(old, { key, hash, value: key.toLowerCase() });
}
const before = JSON.stringify(old);
const next = Array(8).fill(null);
for (const e of old) if (e !== null) place(next, e);
assert.equal(JSON.stringify(old), before);
assert.deepEqual(next.filter(Boolean).map(e => e.key).sort(), ["A", "B", "C"]);
for (let i = 0; i < next.length; i++) {
const e = next[i];
if (e) assert.equal(e.d, (i - (e.hash & 7)) & 7);
}
console.log(next.map((e, i) => e ? `${e.key}@${i}/${e.d}` : null)
.filter(Boolean).join(" "));C@3/0 A@4/1 B@7/0
七、把边界集中进一个可运行接口
完整类提供 set、get、has、delete、size 和 capacity;entries 返回当前物理槽位顺序的键值对数组快照,不承诺原生 Map 的插入顺序,也不是活迭代器。snapshot 是审查辅助接口,复制槽位记录但不深拷贝存储值;修改快照中的 d 不会污染表,修改其中引用的业务对象仍会修改那个对象。值可以是任意 JavaScript 值,存在性必须由 has 判断,不能通过 get 是否返回 undefined 推断。
构造参数依次为初始容量、散列函数和最大容量,容量均须是四到一百零四万八千五百七十六之间的二次幂,初始值不得超过最大值。实现只增长、不自动缩容。最大容量与负载边界一起限制可插入的不同键数量;表达到上限后,更新已有键与删除键仍然允许。
可注入的散列函数用于强制碰撞测试,契约是对同一个字符串稳定返回零到 0xffffffff 之间的整数,并且没有修改容器的副作用。返回值类型与范围会被检查,同一次散列回调里再次调用按键接口会被拒绝;稳定性本身无法靠一次运行验证。随机散列、依赖变化的外部状态或者试图在回调里操作容器,都不属于受支持输入。默认散列满足这个确定性约束。
check 同时检查记录数、负载、重复键、由位置重新计算的距离,以及每条记录是否能被查到。它是调试证据,不应被误认成对所有可能执行的数学证明。特别要关注 #put、#find 与 delete 的循环都有显式上界;有效负载保证保留空槽,循环边界则让意外损坏不会导致无限探测。
示例 07,独立运行输出如下。
"use strict";
const assert = require("node:assert/strict");
function stringHash(key) {
if (typeof key !== "string") throw new TypeError("string key required");
let h = 2166136261;
for (let i = 0; i < key.length; i++) {
h = Math.imul(h ^ key.charCodeAt(i), 16777619) >>> 0;
}
return h;
}
class RobinHoodMap {
#slots; #size = 0; #hash; #max; #hashing = false;
constructor(capacity = 4, hash = stringHash, maxCapacity = 1048576) {
const valid = n => Number.isInteger(n) && n >= 4 &&
n <= 1048576 && (n & (n - 1)) === 0;
if (!valid(capacity) || !valid(maxCapacity) || capacity > maxCapacity) {
throw new RangeError("power-of-two capacity in [4, 1048576] required");
}
if (typeof hash !== "function") throw new TypeError("hash function required");
this.#slots = Array(capacity).fill(null);
this.#hash = hash;
this.#max = maxCapacity;
}
get size() { return this.#size; }
get capacity() { return this.#slots.length; }
#hashKey(key) {
if (typeof key !== "string") throw new TypeError("string key required");
if (this.#hashing) throw new Error("reentrant hash call");
this.#hashing = true;
try {
const h = this.#hash(key);
if (!Number.isInteger(h) || h < 0 || h > 0xffffffff) {
throw new TypeError("hash must return uint32");
}
return h;
} finally { this.#hashing = false; }
}
#find(key, hash) {
const a = this.#slots, mask = a.length - 1;
let i = hash & mask;
for (let d = 0; d < a.length; d++, i = (i + 1) & mask) {
const e = a[i];
if (e === null || e.d < d) return -1;
if (e.hash === hash && e.key === key) return i;
}
return -1;
}
#put(a, entry) {
const mask = a.length - 1;
let e = { key: entry.key, value: entry.value, hash: entry.hash, d: 0 };
let i = e.hash & mask;
for (let probes = 0; probes < a.length; probes++, i = (i + 1) & mask) {
if (a[i] === null) { a[i] = e; return; }
if (a[i].d < e.d) [a[i], e] = [e, a[i]];
e.d++;
}
throw new Error("invariant: no empty slot");
}
set(key, value) {
const hash = this.#hashKey(key), i = this.#find(key, hash);
if (i !== -1) { this.#slots[i].value = value; return this; }
const e = { key, value, hash };
if (this.#size + 1 > this.capacity * 3 / 4) {
if (this.capacity === this.#max) throw new RangeError("capacity limit");
const next = Array(this.capacity * 2).fill(null);
for (const old of this.#slots) if (old !== null) this.#put(next, old);
this.#put(next, e);
this.#slots = next;
} else { this.#put(this.#slots, e); }
this.#size++;
return this;
}
has(key) { return this.#find(key, this.#hashKey(key)) !== -1; }
get(key) {
const i = this.#find(key, this.#hashKey(key));
return i === -1 ? undefined : this.#slots[i].value;
}
delete(key) {
let hole = this.#find(key, this.#hashKey(key));
if (hole === -1) return false;
const a = this.#slots, mask = a.length - 1;
for (let steps = 0; steps < a.length; steps++) {
const next = (hole + 1) & mask, e = a[next];
if (e === null || e.d === 0) {
a[hole] = null;
this.#size--;
return true;
}
a[hole] = e;
e.d--;
hole = next;
}
throw new Error("invariant: deletion did not stop");
}
entries() {
return this.#slots.filter(e => e !== null).map(e => [e.key, e.value]);
}
snapshot() { return this.#slots.map(e => e === null ? null : { ...e }); }
check() {
const a = this.#slots, mask = a.length - 1, keys = new Set();
for (let i = 0; i < a.length; i++) {
const e = a[i];
if (e === null) continue;
if (keys.has(e.key) || e.d !== ((i - (e.hash & mask)) & mask) ||
this.#find(e.key, e.hash) !== i) throw new Error("broken invariant");
keys.add(e.key);
}
if (keys.size !== this.#size || this.#size > a.length * 3 / 4) {
throw new Error("broken size or load");
}
return true;
}
}
const t = new RobinHoodMap(4, () => 3, 8);
t.set("A", 1).set("B", undefined).set("C", 3);
assert.equal(t.capacity, 4);
t.set("A", 10); // Updating an existing key does not grow.
assert.equal(t.capacity, 4);
t.set("D", 4); // The fourth distinct key triggers growth.
assert.equal(t.capacity, 8);
assert.equal(t.has("B"), true);
assert.equal(t.get("B"), undefined);
assert.equal(t.delete("A"), true);
assert.equal(t.delete("A"), false);
assert.equal(t.get("C"), 3);
assert.equal(t.check(), true);
console.log(`size=${t.size}; capacity=${t.capacity}; B is present with undefined`);size=3; capacity=8; B is present with undefined
八、与 Map 做差分,要比较承诺的语义
让 AI 自己为实现写三条示例,往往只会验证它想到了的路径。这里另外维护一个原生 Map,把相同的字符串键和值送进两个容器,每次操作后比较 size、has、get 和 delete 的返回值。对于 values,使用 Object.is 保留 NaN、负零和对象引用等区别;undefined 的值与缺失状态则通过 has 分开验证。
差分只比较本实现承诺支持的部分。原生 Map 接受其他类型的键,也有规范规定的遍历行为;本文的物理槽位快照没有这些承诺,因此不会拿数组顺序硬做相等断言。原生行为参照 ECMAScript 的 Map 章节。它在这里是结果对照,不是我们推测其内部结构的证据。
随机源固定种子,失败时能复现同一串操作;从生成数的不同位段取操作与键,避免简单低位模式让测试只覆盖少数搭配。三种散列模式分别使用默认函数、所有键同槽、只保留两位的集中碰撞。每种模式执行一万次混合操作,并在每一步检查全部候选键,防止只验证当前键而漏掉交换过程中被挤丢的邻居。这个计数是已执行测试的覆盖规模,不是对所有输入正确性的保证。
示例 08,独立运行输出如下。
"use strict";
const assert = require("node:assert/strict");
function stringHash(key) {
if (typeof key !== "string") throw new TypeError("string key required");
let h = 2166136261;
for (let i = 0; i < key.length; i++) {
h = Math.imul(h ^ key.charCodeAt(i), 16777619) >>> 0;
}
return h;
}
class RobinHoodMap {
#slots; #size = 0; #hash; #max; #hashing = false;
constructor(capacity = 4, hash = stringHash, maxCapacity = 1048576) {
const valid = n => Number.isInteger(n) && n >= 4 &&
n <= 1048576 && (n & (n - 1)) === 0;
if (!valid(capacity) || !valid(maxCapacity) || capacity > maxCapacity) {
throw new RangeError("power-of-two capacity in [4, 1048576] required");
}
if (typeof hash !== "function") throw new TypeError("hash function required");
this.#slots = Array(capacity).fill(null);
this.#hash = hash;
this.#max = maxCapacity;
}
get size() { return this.#size; }
get capacity() { return this.#slots.length; }
#hashKey(key) {
if (typeof key !== "string") throw new TypeError("string key required");
if (this.#hashing) throw new Error("reentrant hash call");
this.#hashing = true;
try {
const h = this.#hash(key);
if (!Number.isInteger(h) || h < 0 || h > 0xffffffff) {
throw new TypeError("hash must return uint32");
}
return h;
} finally { this.#hashing = false; }
}
#find(key, hash) {
const a = this.#slots, mask = a.length - 1;
let i = hash & mask;
for (let d = 0; d < a.length; d++, i = (i + 1) & mask) {
const e = a[i];
if (e === null || e.d < d) return -1;
if (e.hash === hash && e.key === key) return i;
}
return -1;
}
#put(a, entry) {
const mask = a.length - 1;
let e = { key: entry.key, value: entry.value, hash: entry.hash, d: 0 };
let i = e.hash & mask;
for (let probes = 0; probes < a.length; probes++, i = (i + 1) & mask) {
if (a[i] === null) { a[i] = e; return; }
if (a[i].d < e.d) [a[i], e] = [e, a[i]];
e.d++;
}
throw new Error("invariant: no empty slot");
}
set(key, value) {
const hash = this.#hashKey(key), i = this.#find(key, hash);
if (i !== -1) { this.#slots[i].value = value; return this; }
const e = { key, value, hash };
if (this.#size + 1 > this.capacity * 3 / 4) {
if (this.capacity === this.#max) throw new RangeError("capacity limit");
const next = Array(this.capacity * 2).fill(null);
for (const old of this.#slots) if (old !== null) this.#put(next, old);
this.#put(next, e);
this.#slots = next;
} else { this.#put(this.#slots, e); }
this.#size++;
return this;
}
has(key) { return this.#find(key, this.#hashKey(key)) !== -1; }
get(key) {
const i = this.#find(key, this.#hashKey(key));
return i === -1 ? undefined : this.#slots[i].value;
}
delete(key) {
let hole = this.#find(key, this.#hashKey(key));
if (hole === -1) return false;
const a = this.#slots, mask = a.length - 1;
for (let steps = 0; steps < a.length; steps++) {
const next = (hole + 1) & mask, e = a[next];
if (e === null || e.d === 0) {
a[hole] = null;
this.#size--;
return true;
}
a[hole] = e;
e.d--;
hole = next;
}
throw new Error("invariant: deletion did not stop");
}
entries() {
return this.#slots.filter(e => e !== null).map(e => [e.key, e.value]);
}
snapshot() { return this.#slots.map(e => e === null ? null : { ...e }); }
check() {
const a = this.#slots, mask = a.length - 1, keys = new Set();
for (let i = 0; i < a.length; i++) {
const e = a[i];
if (e === null) continue;
if (keys.has(e.key) || e.d !== ((i - (e.hash & mask)) & mask) ||
this.#find(e.key, e.hash) !== i) throw new Error("broken invariant");
keys.add(e.key);
}
if (keys.size !== this.#size || this.#size > a.length * 3 / 4) {
throw new Error("broken size or load");
}
return true;
}
}
let seed = 20261019;
function rnd() {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
return seed;
}
const keys = ["", "__proto__", "é", "e\u0301", "\ud800", "😀",
...Array.from({ length: 58 }, (_, i) => `k${i}`)];
const marker = {};
const values = [undefined, null, NaN, -0, 0, false, "v", marker];
for (const hash of [stringHash, () => 7, k => stringHash(k) & 3]) {
const t = new RobinHoodMap(4, hash), ref = new Map();
for (let step = 0; step < 10000; step++) {
const key = keys[(rnd() >>> 8) % keys.length];
const op = (rnd() >>> 12) % 4;
if (op < 2) {
const value = values[(rnd() >>> 7) % values.length];
assert.equal(t.set(key, value), t);
ref.set(key, value);
} else if (op === 2) {
assert.equal(t.delete(key), ref.delete(key));
} else {
assert.equal(t.has(key), ref.has(key));
assert.ok(Object.is(t.get(key), ref.get(key)));
}
assert.equal(t.size, ref.size);
assert.equal(t.check(), true);
for (const k of keys) {
assert.equal(t.has(k), ref.has(k));
assert.ok(Object.is(t.get(k), ref.get(k)));
}
const snapshot = new Map(t.entries());
assert.equal(snapshot.size, ref.size);
for (const [k, v] of ref) assert.ok(Object.is(snapshot.get(k), v));
}
}
console.log("differential: 30000 operations passed across 3 hash modes");differential: 30000 operations passed across 3 hash modes
九、穷举删除次序,并检查失败后的原状态
随机测试擅长组合操作,穷举则适合压紧小规模边界。下面用三个键、四种 home,枚举六十四种散列布局,以及每种布局的全部六种插入顺序和六种删除顺序,共二千三百零四个完整案例。每次插入和删除后都比较尚存键与已删键,所以删除聚簇头部、内部与尾部都必须交出一致结果。
这段穷举本身不会触发扩容:三个键刚好达到四槽表的负载边界。因此扩容证据必须来自第七段的阈值案例、第八段的混合操作,以及独立复核中另外枚举的四键布局,不能把“小表穷举通过”偷换成“扩容也被穷举覆盖”。例末还专门把最大容量设为四,验证第四个新键被拒绝后,槽位快照逐项相同;随后更新 A 依然成功。
审阅一份 AI 生成的数据结构时,可以把问题落在这些可反驳的命题上:缺失查找能否停,删除是否保留后续路径,扩容是否重算位置,重复写入是否只改值,报错是否留下一半完成的状态。要求模型给出具体反例和可运行断言,比接受一句“已考虑边界情况”更容易形成可靠的验收记录。
示例 09,独立运行输出如下。
"use strict";
const assert = require("node:assert/strict");
function stringHash(key) {
if (typeof key !== "string") throw new TypeError("string key required");
let h = 2166136261;
for (let i = 0; i < key.length; i++) {
h = Math.imul(h ^ key.charCodeAt(i), 16777619) >>> 0;
}
return h;
}
class RobinHoodMap {
#slots; #size = 0; #hash; #max; #hashing = false;
constructor(capacity = 4, hash = stringHash, maxCapacity = 1048576) {
const valid = n => Number.isInteger(n) && n >= 4 &&
n <= 1048576 && (n & (n - 1)) === 0;
if (!valid(capacity) || !valid(maxCapacity) || capacity > maxCapacity) {
throw new RangeError("power-of-two capacity in [4, 1048576] required");
}
if (typeof hash !== "function") throw new TypeError("hash function required");
this.#slots = Array(capacity).fill(null);
this.#hash = hash;
this.#max = maxCapacity;
}
get size() { return this.#size; }
get capacity() { return this.#slots.length; }
#hashKey(key) {
if (typeof key !== "string") throw new TypeError("string key required");
if (this.#hashing) throw new Error("reentrant hash call");
this.#hashing = true;
try {
const h = this.#hash(key);
if (!Number.isInteger(h) || h < 0 || h > 0xffffffff) {
throw new TypeError("hash must return uint32");
}
return h;
} finally { this.#hashing = false; }
}
#find(key, hash) {
const a = this.#slots, mask = a.length - 1;
let i = hash & mask;
for (let d = 0; d < a.length; d++, i = (i + 1) & mask) {
const e = a[i];
if (e === null || e.d < d) return -1;
if (e.hash === hash && e.key === key) return i;
}
return -1;
}
#put(a, entry) {
const mask = a.length - 1;
let e = { key: entry.key, value: entry.value, hash: entry.hash, d: 0 };
let i = e.hash & mask;
for (let probes = 0; probes < a.length; probes++, i = (i + 1) & mask) {
if (a[i] === null) { a[i] = e; return; }
if (a[i].d < e.d) [a[i], e] = [e, a[i]];
e.d++;
}
throw new Error("invariant: no empty slot");
}
set(key, value) {
const hash = this.#hashKey(key), i = this.#find(key, hash);
if (i !== -1) { this.#slots[i].value = value; return this; }
const e = { key, value, hash };
if (this.#size + 1 > this.capacity * 3 / 4) {
if (this.capacity === this.#max) throw new RangeError("capacity limit");
const next = Array(this.capacity * 2).fill(null);
for (const old of this.#slots) if (old !== null) this.#put(next, old);
this.#put(next, e);
this.#slots = next;
} else { this.#put(this.#slots, e); }
this.#size++;
return this;
}
has(key) { return this.#find(key, this.#hashKey(key)) !== -1; }
get(key) {
const i = this.#find(key, this.#hashKey(key));
return i === -1 ? undefined : this.#slots[i].value;
}
delete(key) {
let hole = this.#find(key, this.#hashKey(key));
if (hole === -1) return false;
const a = this.#slots, mask = a.length - 1;
for (let steps = 0; steps < a.length; steps++) {
const next = (hole + 1) & mask, e = a[next];
if (e === null || e.d === 0) {
a[hole] = null;
this.#size--;
return true;
}
a[hole] = e;
e.d--;
hole = next;
}
throw new Error("invariant: deletion did not stop");
}
entries() {
return this.#slots.filter(e => e !== null).map(e => [e.key, e.value]);
}
snapshot() { return this.#slots.map(e => e === null ? null : { ...e }); }
check() {
const a = this.#slots, mask = a.length - 1, keys = new Set();
for (let i = 0; i < a.length; i++) {
const e = a[i];
if (e === null) continue;
if (keys.has(e.key) || e.d !== ((i - (e.hash & mask)) & mask) ||
this.#find(e.key, e.hash) !== i) throw new Error("broken invariant");
keys.add(e.key);
}
if (keys.size !== this.#size || this.#size > a.length * 3 / 4) {
throw new Error("broken size or load");
}
return true;
}
}
function permutations(a) {
if (a.length === 0) return [[]];
return a.flatMap((x, i) => permutations(a.filter((_, j) => i !== j))
.map(rest => [x, ...rest]));
}
const keys = ["A", "B", "C"], orders = permutations(keys);
let cases = 0;
for (let code = 0; code < 64; code++) {
const homes = new Map(keys.map((k, i) => [k, (code >>> (2 * i)) & 3]));
for (const insertion of orders) for (const deletion of orders) {
const t = new RobinHoodMap(4, k => homes.get(k)), ref = new Map();
const verify = () => {
t.check();
assert.equal(t.size, ref.size);
for (const k of keys) {
assert.equal(t.has(k), ref.has(k));
assert.equal(t.get(k), ref.get(k));
}
};
for (const k of insertion) { t.set(k, k); ref.set(k, k); verify(); }
for (const k of deletion) {
assert.equal(t.delete(k), ref.delete(k)); verify();
}
cases++;
}
}
const bounded = new RobinHoodMap(4, () => 0, 4);
bounded.set("A", 1).set("B", 2).set("C", 3);
const before = bounded.snapshot();
assert.throws(() => bounded.set("D", 4), RangeError);
assert.deepEqual(bounded.snapshot(), before);
bounded.set("A", 9);
assert.equal(bounded.get("A"), 9);
assert.equal(bounded.check(), true);
console.log(`exhaustive: ${cases} insertion/deletion cases; capacity failure is unchanged`);exhaustive: 2304 insertion/deletion cases; capacity failure is unchanged
交付前再核对四件事
路径证据:距离按当前容量计算,提前停止使用严格小于,回移只跨越正距离记录。
状态证据:已有键更新不扩容,失败新增不改变状态,临时扩容完成后才替换旧数组。
契约证据:仅原始字符串键,值可为 undefined,散列函数稳定,快照不保证插入顺序。
边界证据:循环有界,容量受限,碰撞、绕回、删除顺序、重复写入和扩容分别有测试。
本文保留了小容器容易被忽略的代价:需要读取整个字符串计算散列,碰撞集中时会访问多个槽,回移删除会搬动记录,重建也要重新安置已有数据。没有测量就不作吞吐、内存或相对原生 Map 的结论。真正的审查成果,是每一个状态变化都有明确的前提、停止条件和可复现的检查方式。

