Explore Library
Code Quiz

Hash Map Chaining Update Bug

Spot the collision-handling flaw in this separate-chaining hash map implementation.

Codejavascript
class HashMap {
  constructor(size = 16) {
    this.buckets = Array.from({ length: size }, () => []);
  }

  _hash(key) {
    let h = 0;
    for (const ch of String(key)) h = (h * 31 + ch.charCodeAt(0)) % this.buckets.length;
    return h;
  }

  set(key, value) {
    const bucket = this.buckets[this._hash(key)];
    bucket.push([key, value]);
  }

  get(key) {
    const bucket = this.buckets[this._hash(key)];
    for (const [k, v] of bucket) {
      if (k === key) return v;
    }
    return undefined;
  }
}

const m = new HashMap();
m.set('a', 1);
m.set('a', 2);
console.log(m.get('a'));

What is the bug in this hash map implementation?