Testing Insert Method
https://subscription.packtpub.com/video/programming/9781800206878/p4/video4_6/-testing-insert-method
by Dominic Myers
JavaScript
function HashTable(size) {
this.buckets = Array(size);
this.numBuckets = this.buckets.length;
}
function HashNode(key, value, next) {
this.key = key;
this.value = value;
this.next = next || null;
}
HashTable.prototype.hash = function(key) {
var total = 0;
for (var i = 0; i < key.length; i++) {
total += key.charCodeAt(i)
}
var bucket = total % this.numBuckets;
return bucket;
}
HashTable.prototype.insert = function(key, value) {
var index = this.hash(key);
console.log("INDEX: ", index)
if (!this.buckets[index]) this.buckets[index] = new HashNode(key, value);
else {
var currentNode = this.buckets[index];
while (currentNode.next) {
currentNode = currentNode.next
}
currentNode.next = new HashNode(key, value);
}
}
var myHT = new HashTable(30);
myHT.insert("Dean", "[email protected]");
myHT.insert("Megan", "[email protected]");
myHT.insert("Dane", "[email protected]");
console.log(myHT.buckets)