I am trying to implement a hash table using javascript. At the moment, everything is working so far, but I am having trouble with my get method to retrieve a value in the hash table given a specific key. I am using linear probing in order to avoid collisions. When I hash the key "Alejandro" I map the key to the 0 index. Then I add it into my hash table. Then I try "Rosalby" which also maps to 0 index. I used linear probing to find the next available slot, in my case the empty index is 1 and I put Rosalby's value in that slot. So far it seems that I am managing my collision well. However; when I try to get the values in my get method, I am unable to get the right values here is what my hash table looks like.
Also, I would like to mention that I have made my hash table bigger in size and I get the right value given specific key, simply because I do not have collision. Thank you in advance.
// Hash table implementation
class HashTable {
// constructor functio
constructor(size) {
this.size = size;
this.buckets = this.initArray(size);
this.limit = 0;
}
// init array function
initArray(size) {
// init an array
const array = [];
// populate the array base on the size
for (let i = 0; i < size; i++) {
// push null to the array
array.push(null);
}
// return the array
return array;
}
// mapping key to index
hash(key) {
let total = 0;
// get unique code of character in the string
for (let i = 0; i < key.length; i++) {
let keyCode = key.charCodeAt(i)
// console.log("Key code:", keyCode)
// sum up the unique code
total += keyCode;
// console.log(total);
}
// mod the total to the size of the hash table
const hashIndex = total % this.size;
// return that index
return hashIndex;
}
// put method
put(key, value) {
// throw an erro if hashTable is full
if (this.limit >= this.size) throw "Hash Table is full";
// hash the key
let hashIndex = this.hash(key);
// console.log(hashIndex);
// linear probing
while (this.buckets[hashIndex] != null) {
hashIndex++;
hashIndex = hashIndex % this.size;
}
// add the value at that key to the buckets array
this.buckets[hashIndex] = value;
// increase the limit
this.limit++;
}
// get method
get(key) {
// hash the key
let hashIndex = this.hash(key);
let value = this.buckets[hashIndex];
// return the value at that index
return value;
}
} // end of hash table
// sanity check
const ht = new HashTable(3);
console.log(ht);
// ht.hash("Rosalby");
console.log();
ht.put("Alejandro", "555-5555");
ht.put("Rosalby", "123-1231");
ht.put("Lalaland", "000-0000");
// ht.put("Lalaland", "919-1919");
console.log();
console.log(ht);
console.log("Alejandro:", ht.get("Alejandro"), "Rosalby:", ht.get("Rosalby"), "Lalaland:", ht.get("Lalaland"));