Created
January 27, 2019 14:38
-
-
Save bflannery/af7d1ae0d8a542d62eab933c6327c784 to your computer and use it in GitHub Desktop.
ES6 Hash Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HashTable { | |
constructor(size) { | |
this.buckets = Array(size); | |
this.numBuckets = this.buckets.length; | |
} | |
hash() { | |
var total = 0; | |
for (var i = 0; i < key.length; i++) { | |
total += key.charCodeAt(i); | |
} | |
return total % this.numBuckets; | |
} | |
insert() { | |
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); | |
} | |
} | |
get() { | |
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; | |
} | |
} | |
retrieveAll() { | |
var allNodes = [] | |
for (i = 0; i < this.numBuckets; i++) { | |
var currentNode = this.buckets[i]; | |
while (currentNode) { | |
allNodes.push(currentNode); | |
currentNode = currentNode.next | |
} | |
} | |
return allNodes; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment