实现说明
哈希表开放寻址双哈希(JavaScript)可以归结为类 HashTable。
for (let i = 0; i < this.size; i++) 是唯一的迭代点——其余代码顺序执行一遍。这不是输入检查:Error 在耗尽路径上,循环跑完才会执行。
使用要点
- 守卫
this.keys[idx] === null || this.keys[idx] === key一旦成立就走提前的return,把后续流程挡掉。
常见问题
这里有失败路径吗?
不是坏输入触发的:Error 在循环之后,只有循环跑完才会执行。
不安装任何包也能运行吗?
可以,开箱即跑——没有引用任何内建 API 之外的东西。
核心语句
h2(key) { let h = 0; for (const c of String(key)) h = (h * 17 + c.charCodeAt(0)) % (this.size - 1); return h + 1; }
h1(key) { let h = 0; for (const c of String(key)) h = (h * 31 + c.charCodeAt(0)) % this.size; return h; }
get(key) { const i = this.findSlot(key); return this.keys[i] === key ? this.vals[i] : undefined; }
代码示例
class HashTable {
constructor(size = 101) {
this.size = size;
this.keys = new Array(size).fill(null);
this.vals = new Array(size).fill(null);
}
h1(key) { let h = 0; for (const c of String(key)) h = (h * 31 + c.charCodeAt(0)) % this.size; return h; }
h2(key) { let h = 0; for (const c of String(key)) h = (h * 17 + c.charCodeAt(0)) % (this.size - 1); return h + 1; }
findSlot(key) {
const step = this.h2(key);
let idx = this.h1(key);
for (let i = 0; i < this.size; i++) {
if (this.keys[idx] === null || this.keys[idx] === key) return idx;
idx = (idx + step) % this.size;
}
throw new Error("table full");
}
set(key, val) { const i = this.findSlot(key); this.keys[i] = key; this.vals[i] = val; }
get(key) { const i = this.findSlot(key); return this.keys[i] === key ? this.vals[i] : undefined; }
}