← 中文资源

简体中文版本

泛型哈希表双哈希

该资源提供 ts-hash-table-open-addr-p16 的中文技术参考,涵盖核心方法、参数说明与使用示例

阅读英文原文

实现说明

活动部件是类 HashTable。 for (let i = 0; i < this.size; i++) { if (this.keys[idx] === null || this.keys[idx] === key) { th… 承担全部的逐项处理。Error 在其所在位置无条件抛出——前面没有任何输入检查。

使用要点

  • 守卫 this.keys[idx] === null 命中后立刻用提前的 return 结束这一轮。

常见问题

异常是由什么触发的?

不会。Error 不在任何守卫之后——只要执行到那行代码就会触发。

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。

核心语句

throw new Error("table full");

代码示例

class HashTable<K, V> {
  private keys: (K | null)[]; private vals: (V | null)[]; private size: number;
  constructor(size = 101) { this.size = size; this.keys = new Array(size).fill(null); this.vals = new Array(size).fill(null); }
  private h1(key: K): number { const s = String(key); let h = 0; for (const c of s) h = (h * 31 + c.charCodeAt(0)) % this.size; return h; }
  private h2(key: K): number { const s = String(key); let h = 0; for (const c of s) h = (h * 17 + c.charCodeAt(0)) % (this.size - 1); return h + 1; }
  set(key: K, val: V): void {
    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) { this.keys[idx] = key; this.vals[idx] = val; return; } idx = (idx + step) % this.size; }
    throw new Error("table full");
  }
  get(key: K): V | undefined { const step = this.h2(key); let idx = this.h1(key); for (let i = 0; i < this.size; i++) { if (this.keys[idx] === null) return undefined; if (this.keys[idx] === key) return this.vals[idx]!; idx = (idx + step) % this.size; } return undefined; }
}