Created
October 8, 2017 13:04
-
-
Save MathRivest/d3b6bf8ea839cf3cc285f9a048951752 to your computer and use it in GitHub Desktop.
hashtable-es6 created by mathrivest - https://repl.it/L7T7/8
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(key) { | |
let total = 0; | |
for (var i = 0; i < key.length; i++) { | |
total += key.charCodeAt(i); | |
} | |
var bucket = total % this.numBuckets; | |
return bucket; | |
} | |
insert(key, value) { | |
let index = this.hash(key), | |
newNode = new HashNode(key, value); | |
if (!this.buckets[index]) { | |
this.buckets[index] = newNode; | |
} 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 = newNode; | |
} | |
} | |
get(key) { | |
let index = this.hash(key); | |
if(!this.buckets[index]) { | |
return null; | |
} else { | |
let currentNode = this.buckets[index]; | |
while(currentNode) { | |
if(currentNode.key === key) { | |
return currentNode.value; | |
} | |
currentNode = currentNode.next; | |
} | |
return null; | |
} | |
} | |
retrieveAll() { | |
let allNodes = []; | |
for (var i = 0; i< this.numBuckets; i++) { | |
let currentNode = this.buckets[i]; | |
while(currentNode) { | |
allNodes.push(currentNode); | |
currentNode = currentNode.next; | |
} | |
} | |
return allNodes; | |
} | |
} | |
function HashNode(key, value, next) { | |
this.key = key; | |
this.value = value; | |
this.next = next || null; | |
} | |
const myHT = new HashTable(30); | |
myHT.insert('Steve', 'steve@allo.com'); | |
myHT.insert('Paul', 'paul@allo.com'); | |
myHT.insert('Jerry', 'jerry.allo@allo.com'); | |
myHT.insert('Dane', 'dane@allo.com'); | |
myHT.insert('Dean', 'dean@allo.com'); | |
myHT.insert('Jerry', 'jerry@gmail.com'); | |
myHT.insert('Dane', 'dane@gmail.com'); | |
myHT.insert('Dean', 'dean@gmail.com'); | |
console.log(myHT); | |
console.log(myHT.retrieveAll()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment