Hash Table Open Addressing Double Hash (JavaScript)
Implement a hash table with open addressing and double hashing for collision resolution supporting insert, lookup, and delete.
Code
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; }
}How it works
Hash Table Open Addressing Double Hash (JavaScript) keeps everything in the class HashTable.
The file repeats itself only inside for (let i = 0; i < this.size; i++). Not an input check: Error is thrown on the exhaustion path, after the loop finishes without a successful exit.
Points of care
- The guard
this.keys[idx] === null || this.keys[idx] === keyshort-circuits the flow with an earlyreturnwhen its condition holds.
Statements that matter
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; }
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
- Is there a failure path here?
- After loop exhaustion, not on bad input: the `Error` sits after the loop and runs only when the loop finishes.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced.
Report a problem with this exampleOpens a pre-filled issue on GitHub.