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; }
}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] === nullshort-circuits the flow with an earlyreturnwhen its condition holds.
Key statements
throw new Error("table full");
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.