When adding elements to a hash table the most crucial part is collision resolution. We're going to use chaining for the same. There are other algorithms you can read about here: https://en.wikipedia.org/wiki/Hash_table#Collision_resolution
Now let's look at the implementation. We'll be creating a hash function that'll work on integers only to keep this simple. But a more complex algorithm can be used to hash every object −
Example
put(key, value) {
let hashCode = 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));
}You can test this using
Example
let ht = new HashTable(); ht.put(10, 94); ht.put(20, 72); ht.put(30, 1); ht.put(21, 6); ht.put(15, 21); ht.put(32, 34); ht.display();
Output
This will give the output −
0:
1:
2:
3:
4: { 15: 21 }
5:
6:
7:
8: { 30: 1 }
9: { 20: 72 }
10: { 10: 94 } -->{ 21: 6 } -->{ 32: 34 }