I am trying to create an insert() function to add key-value pairs to the hash table, and in case of collisions I use a linked list. I want to be able to update a key value pair if I find that the entry with this key already exists.
For some reason I cannot access the keys by doing something like this.data[index].key
How do I parse the pairs and compare the keys?
const sha256 = require('js-sha256');
class KeyValuePair {
constructor(key, value) {
this.key = key;
this.value = value;
this.next = null;
}
}
class HashTable {
constructor(numBuckets) {
// Your code here
this.count = 0;
this.capacity = numBuckets;
this.data = new Array(numBuckets);
for(let i = 0; i < numBuckets; i++){
this.data[i] = null;
}
}
hash(key) {
// Your code here
let hashed = sha256(key);
let finalHashInt = parseInt(hashed.slice(0, 8), 16); //parseInt converts this hexadeciam slice to deciaml number
return finalHashInt;
}
hashMod(key) {
// Your code here
return this.hash(key) % this.capacity;
}
insert(key, value) {
// Your code here
//console.log("Im here")
const newPair = new KeyValuePair(key, value);
const index = this.hashMod(key);
let current;
current = this.data[index];
// console.log(current['key']);
if(this.data[index] !== null){
while(current.next !== null){
console.log(key)
if(current.key === key){
this.data[index] = newPair;
return;
}
current = current.next;
}
newPair.next = this.data[index];
this.data[index] = newPair;
this.count++;
}
else{
this.data[index] = newPair;
this.count++;
}
}