Skip to content

Instantly share code, notes, and snippets.

@aelshamy
Created December 27, 2016 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aelshamy/f2f02bd955f79a826a915dd06e9ad01a to your computer and use it in GitHub Desktop.
Save aelshamy/f2f02bd955f79a826a915dd06e9ad01a to your computer and use it in GitHub Desktop.
Hash Table Data Structure created by aelshamy - https://repl.it/ExRG/2
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);
}
return (total % this.numBuckets);
}
HashTable.prototype.insert = function (key, value){
var index = this.hash(key);
if(!this.buckets[index]) this.buckets[index] = new HashNode(key, value);
else if(this.buckets[index].key === key) {
this.buckets[index].value = value;
}
else{
var 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);
}
}
HashTable.prototype.get = function (key){
var index = this.hash(key);
if(!this.buckets[index]) return null;
else{
var currentNode = this.buckets[index];
while(currentNode){
if(currentNode.key === key) return currentNode.value;
currentNode = currentNode.next;
}
return null;
}
}
HashTable.prototype.retreiveAll = function (){
var allNodes = [];
for(var i= 0; i<this.numBuckets; i++){
var currentNode = this.buckets[i];
while(currentNode){
allNodes.push(currentNode);
currentNode = currentNode.next;
}
}
return allNodes;
}
var myHT = new HashTable(30);
myHT.insert('Dean', 'dean@gmail.com');
myHT.insert('Megan', 'megan@gmail.com');
myHT.insert('Dane', 'dane@gmail.com');
myHT.insert('Daen', 'dane@gmail.com');
myHT.insert('Amr', 'amr@gmail.com');
console.log(myHT.get('Megan'));
console.log(myHT.retreiveAll());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment