Building a Hash Table from Scratch
Explore the process of constructing a hash table from scratch in JavaScript by implementing a bucket chaining strategy to handle collisions. Understand how to create hash entries and the hash table class while managing resizing and hash functions to optimize data storage and retrieval.
We'll cover the following...
Hash Table Using Bucket Chaining
We will use the chaining strategy along with the resize operation to avoid collisions in the table.
All elements with the same hash key will be stored in an array at that index. In data structures, these arrays are called buckets. The size of the hash table is set as n*m where n is the number of keys it can hold, and m is the number of slots each bucket contains. Each slot holds a key/value pair.
Implementation
We will start by building a simple HashEntry class. As discussed earlier, a typical hash entry consists of three data members: the key, the value and the reference to a new entry. Here’s how we will code this in JavaScript:
Now, we’ll create the HashTable class which is a collection of HashEntry objects. We will also keep track of the total number of slots in the hash table and the current size of the hash table. These two variables will come in handy when we need to resize the table.
Here is the basic implementation in JavaScript:
The last thing we need is a hash function. We tried out some different approaches in the previous lessons. For our implementation, we will simply take the modular of the key with the total size of the hash table (slots).