I try to return all nodes from a hash function.
So I have it like this:
class HasTable {
constructor(size) {
this.buckets = Array(size);
this.numBuckets = this.buckets.length;
}
hash(key) {
let sum = 0;
for (let i = 0; i < key.length; i++) {
sum += key.charCodeAt(i);
}
let bucket = sum % this.numBuckets;
return bucket;
}
insert(key, value) {
let index = this.hash(key);
console.log("INDEX", index);
if (!this.buckets[index]) this.buckets[index] = new HashNode(key, value);
else if (this.buckets[index].key === key) {
this.buckets[index].value = value;
} else {
let currentNode = this.buckets[index];
while (currentNode.next) {
if (currentNode.next.key === key) {
currentNode.next.value = value;
return;
}
currentNode = currentNode.next;
}
currentNode.next = new HashNode(key, value);
}
}
get(key) {
let index = this.hash(key);
if (!this.buckets[index]) return null;
else {
let currentNode = this.buckets[index];
while (currentNode) {
if (this.buckets[index].key === key) return currentNode.value;
currentNode.next;
}
return null;
}
}
returnAll() {
let allNodes = [];
for (let i = 0; i < this.numBuckets; i++) {
let currentNode = this.buckets[i];
while (currentNode) {
allNodes.push({key: currentNode.key, value: currentNode.value});
currentNode = currentNode.next;
}
}
return allNodes;
};
}
class HashNode {
constructor(key, value, next) {
this.key = key;
this.value = value;
this.next = next || null;
}
}
let has = new HasTable(30);
has.insert("a", "gmail.com");
has.insert("b", "hotmail.com");
has.insert("b", "hotmailHOTMAIL.com");
has.insert("c", "gstar.com");
has.insert("d", "oke.com");
has.insert("e", "nice.com");
has.insert("e", "nice99.com");
has.insert("e", "nice101.com");
console.log(has.returnAll());
But the output is this:
0: {key: 'a', value: 'gmail.com'}
1: {key: 'b', value: 'hotmailHOTMAIL.com'}
2: {key: 'c', value: 'gstar.com'}
3: {key: 'd', value: 'oke.com'}
4: {key: 'e', value: 'nice101.com'}
Which is of course not correct. Because I have three keys with e
? My desired result is very clear.
I insert eight nodes. But if I call the returnAll method it returns only nodes.
As far as my understanding of the hash table goes, your implementation is behaving correctly. Chained entries are added to the bucket only if entries with different keys are mapped to the same hash. In your case you have entries with the same key inserted over and over, which causes the already existing entry being overwritten. This is done by this piece of your code:
...
else if (this.buckets[index].key === key) {
this.buckets[index].value = value;
}
...
Chained entries would be added for e.g.
has.insert("e", "nice.com");
has.insert("eZ", "nice99.com");