Creating a hash table using Javascript

JavascriptWeb DevelopmentFront End Technology

Let us set up a simple class that we'll use to define all these methods on. We'll create a container object to store the hash table and create a display function to display the table. Note that for collision resolution, we'll use chaining.

The display function takes each entry (hashed value) in the table and prints all pairs associated with it.

Example

We'll also create a new class on the prototype to store the key-value pairs.

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}`);
         });
      }
      hash(key) {
         return key % 11;
      }
   }
   HashTable.prototype.KVPair = class {
      constructor(key, value) {
         this.key = key;
         this.value = value;
      }
   }
}

We're using some advanced features like destructuring in the display method. That helps avoid boilerplate code.

raja
Published on 28-Jun-2018 09:59:17
Advertisements