Created
February 14, 2016 22:28
-
-
Save yoshprogrammer/541668ca5eb05a17e5c0 to your computer and use it in GitHub Desktop.
Hashtables JS
This file contains hidden or 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
var getIndexBelowMaxForKey = function(str, max){ | |
var hash = 0; | |
for (var i = 0; i < str.length; i++) { | |
hash = (hash<<5) + hash + str.charCodeAt(i); | |
hash = hash & hash; // Convert to 32bit integer | |
hash = Math.abs(hash); | |
} | |
return hash % max; | |
}; | |
function HashTable(storageLimit) { | |
this.storage = []; | |
this.storageLimit = storageLimit || 12; | |
}; | |
HashTable.prototype.insert = function(key, value){ | |
var index = getIndexBelowMaxForKey(key, this.storageLimit); | |
if(this.storage[index] === undefined){ | |
this.storage[index] = [[key, value]]; | |
}else{ | |
var inserted = false; | |
for(var i = 0; i < this.storage[index].length; i++){ | |
if(this.storage[index][i][0] === key){ | |
storage[index][i][1] = value; | |
inserted = true; | |
} | |
} | |
if(inserted === false){ | |
storage[index].push([key,value]); | |
} | |
} | |
}; | |
HashTable.prototype.retrieve = function(key){ | |
var index = getIndexBelowMaxForKey(key, this.storageLimit); | |
if(storage[index] === undefined){ | |
return undefined; | |
}else{ | |
for(var i = 0; i < storage[index].length; i++){ | |
if(storage[index][i][0] === key){ | |
return storage[index][i][1]; | |
} | |
} | |
} | |
}; | |
HashTable.prototype.remove = function(key){ | |
var index = getIndexBelowMaxForKey(key, this.storageLimit); | |
if(storage[index].length === 1 && storage[index][0][0] === key){ | |
delete storage[index]; | |
}else{ | |
for (var i = 0; i < storage[index]; i++){ | |
if(storage[index][i][0] === key){ | |
delete storage[index][i]; | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment