The HashTable Class in Javascript

Here is the complete implementation of the HashTable class. This could of course be improved by using more efficient data structures and collision resolution algorithms.

Example


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  {
         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  {
      // 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;
   }
};
Updated on: 2020-06-15T10:58:43+05:30

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements