Skip to content

Instantly share code, notes, and snippets.

@bflannery
Created January 27, 2019 14:38
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 bflannery/af7d1ae0d8a542d62eab933c6327c784 to your computer and use it in GitHub Desktop.
Save bflannery/af7d1ae0d8a542d62eab933c6327c784 to your computer and use it in GitHub Desktop.
ES6 Hash Table
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