Hash Table Open Addressing Double Hash Typed
Implement a typed hash table with open addressing and double hashing for collision resolution.
Code
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; }
}Report a problem with this exampleOpens a pre-filled issue on GitHub.