Hash Table Open Addressing Double Hash Typed

Implement a typed hash table with open addressing and double hashing for collision resolution.

TypescriptData Integrity

Code

typescriptsnippet
12 lines
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; }
}

What the code does

Hash Table Open Addressing Double Hash Typed is built around the class HashTable.

Iteration happens inside for (let i = 0; i < this.size; i++) { if (this.keys[idx] === null || this.keys[idx] === key) { th… — everything outside it runs once. A Error is thrown unconditionally at its throw site — no input check sits in front of it.

What to watch for

  • The guard this.keys[idx] === null short-circuits the flow with an early return when its condition holds.

Key statements

throw new Error("table full");

Interactive Tools for This Topic

FAQ

What triggers the exception?
No. The `Error` is not behind any guard — it triggers purely on reaching that line of code.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared.