The HashTable Class in Javascript

A HashTable (Hash Map) is a data structure that stores key-value pairs using a hash function to compute array indices. This implementation uses chaining to handle collisions, where multiple values can be stored at the same index using arrays.

Complete HashTable Implementation

class HashTable {
  constructor() {
    this.container = [];
    // Populate the container with empty arrays
    // which can be used to add more elements in
    // cases of collisions
    for (let i = 0; i < 11; i++) {
      this.container.push([]);
    }
  }

  display() {
    this.container.forEach((value, index) => {
      let chain = value
        .map(({ key, value }) => `{ ${key}: ${value} }`)
        .join(" --> ");
      console.log(`${index}: ${chain}`);
    });
  }

  put(key, value) {
    let hashCode = this.hash(key);

    for (let i = 0; i < this.container[hashCode].length; i++) {
      // Replace the existing value with the given key
      // if it already exists
      if (this.container[hashCode][i].key === key) {
        this.container[hashCode][i].value = value;
        return;
      }
    }

    // Push the pair at the end of the array
    this.container[hashCode].push(new this.KVPair(key, value));
  }

  get(key) {
    let hashCode = this.hash(key);
    for (let i = 0; i < this.container[hashCode].length; i++) {
      // Find the element in the chain
      if (this.container[hashCode][i].key === key) {
        return this.container[hashCode][i];
      }
    }
    return undefined;
  }

  remove(key) {
    let hashCode = this.hash(key);

    for (let i = 0; i < this.container[hashCode].length; i++) {
      // Find the element in the chain
      if (this.container[hashCode][i].key === key) {
        this.container[hashCode].splice(i, 1);
        return true;
      }
    }
    return false;
  }

  hash(key) {
    return key % 11;
  }

  forEach(callback) {
    // For each chain
    this.container.forEach(elem => {
      // For each element in each chain call callback on KV pair
      elem.forEach(({ key, value }) => callback(key, value));
    });
  }

  static join(table1, table2) {
    // Check if both args are HashTables
    if (!(table1 instanceof HashTable) || !(table2 instanceof HashTable)) {
      throw new Error("Illegal Arguments");
    }

    let combo = new HashTable();
    table1.forEach((k, v) => combo.put(k, v));
    table2.forEach((k, v) => combo.put(k, v));
    return combo;
  }
}

HashTable.prototype.KVPair = class {
  constructor(key, value) {
    this.key = key;
    this.value = value;
  }
};

// Example usage
let hashTable = new HashTable();

// Adding key-value pairs
hashTable.put(10, "Apple");
hashTable.put(21, "Banana");
hashTable.put(32, "Cherry");
hashTable.put(43, "Date");

console.log("HashTable contents:");
hashTable.display();

console.log("\nRetrieving values:");
console.log("Key 21:", hashTable.get(21));
console.log("Key 99:", hashTable.get(99));

console.log("\nRemoving key 21:");
hashTable.remove(21);
hashTable.display();
HashTable contents:
0: { 21: Banana }
1: { 32: Cherry }
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
10: { 10: Apple } --> { 43: Date }

Retrieving values:
Key 21: { key: 21, value: 'Banana' }
Key 99: undefined

Removing key 21:
0: 
1: { 32: Cherry }
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
10: { 10: Apple } --> { 43: Date }

Key Features

Hash Function: Uses modulo operation (key % 11) to map keys to array indices. This simple hash function works well for numeric keys.

Collision Handling: Uses chaining - each bucket contains an array that can hold multiple key-value pairs with the same hash code.

Core Methods:

  • put(key, value) - Adds or updates a key-value pair
  • get(key) - Retrieves the value for a given key
  • remove(key) - Removes a key-value pair
  • display() - Shows the current state of all buckets

Collision Example

let table = new HashTable();

// These keys will have the same hash code (10 % 11 = 10, 21 % 11 = 10)
table.put(10, "First");
table.put(21, "Second");
table.put(32, "Third");

console.log("Collision handling with chaining:");
table.display();
Collision handling with chaining:
0: 
1: { 32: Third }
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
10: { 10: First } --> { 21: Second }

Conclusion

This HashTable implementation provides basic hash map functionality with collision resolution through chaining. While simple, it demonstrates core concepts and could be enhanced with better hash functions and dynamic resizing for production use.

Updated on: 2026-03-15T23:18:59+05:30

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements