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.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
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] === key short-circuits the flow with an early return when 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

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.