Created
February 19, 2017 16:53
-
-
Save robgmerrill/8883f12264ba7a1ed9db41087f30696a to your computer and use it in GitHub Desktop.
Hash Table Insert by robgmerrill - https://repl.it/FpSK/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
// Hash Table | |
// key value pairs | |
// {key: name, value: number} | |
// constructor function for the table and consturctor function for the node | |
function HashTable(size) { | |
// make a new array of size of choice and assign it to property of buckets | |
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; | |
}; | |
// console.log(myHT); | |
// console.log(myHT.hash('Becca')); | |
// console.log(myHT); | |
// insert method | |
// takes key/value pair and turns into a hash node then placed into correct bucket | |
HashTable.prototype.insert = function(key, value) { | |
var index = this.hash(key); | |
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('Meagan', '[email protected]'); | |
myHT.insert('Dane', '[email protected]'); | |
console.log(myHT.buckets); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment