Skip to content

Commit

Permalink
Complete hashTable.js
Browse files Browse the repository at this point in the history
  • Loading branch information
fay-jai committed Dec 27, 2014
1 parent 60aedbc commit de93247
Showing 1 changed file with 40 additions and 10 deletions.
50 changes: 40 additions & 10 deletions hashTable/hashTable.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,51 @@
* The hashtable does not need to resize but it should still handle collisions.
*/

var makeHashTable = function(){
var result = {};
var storage = [];
var makeHashTable = function () {
var result = {};
var storage = [];
var storageLimit = 1000;

result.insert = function(/*...*/){
// TODO: implement `insert()`
result.insert = function (key, value) {
var idx = getIndexBelowMaxForKey(key, storageLimit);
var bucket = storage[idx] || [];

for (var i = 0; i < bucket.length; i += 1) {
// check if key, value already exists in bucket
if (bucket[i][0] === key) {
bucket[i][1] = value;
return;
}
}

// key, value doesn't exist in bucket
bucket.push( [key, value] );
storage[idx] = bucket;
};

result.retrieve = function(/*...*/){
// TODO: implement `retrieve()`
result.retrieve = function (key) {
var idx = getIndexBelowMaxForKey(key, storageLimit);
var bucket = storage[idx] || [];

for (var i = 0; i < bucket.length; i += 1) {
if (bucket[i][0] === key) {
return bucket[i][1];
}
}

return null;
};

result.remove = function(/*...*/){
// TODO: implement `remove()`
result.remove = function (key) {
var idx = getIndexBelowMaxForKey(key, storageLimit);
var bucket = storage[idx] || [];

for (var i = 0; i < bucket.length; i += 1) {
if (bucket[i][0] === key) {
bucket.splice(i, 1);
break;
}
}
};

return result;
Expand All @@ -26,7 +56,7 @@ var makeHashTable = function(){
// This is a "hashing function". You don't need to worry about it, just use it
// to turn any string into an integer that is well-distributed between
// 0 and max - 1
var getIndexBelowMaxForKey = function(str, max){
var getIndexBelowMaxForKey = function (str, max) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = (hash<<5) + hash + str.charCodeAt(i);
Expand Down

0 comments on commit de93247

Please sign in to comment.