Skip to content

Instantly share code, notes, and snippets.

@TessMyers
Last active August 29, 2015 14:08
Show Gist options
  • Save TessMyers/3c0bf2abc038d28f40fb to your computer and use it in GitHub Desktop.
Save TessMyers/3c0bf2abc038d28f40fb to your computer and use it in GitHub Desktop.
simple HashTable example
// This is an example of a simplified javascript hash table that showcases a neat way (ln 64) to remove entries without
// unneccesary iteration and without leaving undefined values lying around.
// I was too lazy to write a real hashing function, so just pretend that the hash function shown at the bottom works perfectly
var makeHashTable = function(){
var result = {};
result.storage = [];
var storageLimit = 10;
result.insert = function(key, value){
var i = getIndexBelowMaxForKey(key, storageLimit);
// If no bucket, make one
if (!result.storage[i]){
var bucket = [];
bucket.push([key, value]);
result.storage[i] = bucket;
} else {
var length = result.storage[i].length;
// Loop through all items in the bucket, checking for matching keys
for (var j = 0; j < length; j++) {
// If the key is already present, overwrite the value
if (result.storage[i][j][0] === key){
result.storage[i][j][1] = value;
} else {
// else, push in a new tuple containing key:value pair
result.storage[i].push([key, value]);
}
}
}
};
result.retrieve = function(targetKey){
var i = getIndexBelowMaxForKey(targetKey, storageLimit);
var bucket = result.storage[i] || [];
// Loop through bucket and look for matching key
for (var j = 0; j < bucket.length; j++){
// If key is found, return the corresponding value
if (bucket[j][0] === targetKey) {
return bucket[j][1];
}
}
};
result.remove = function(targetKey){
var i = getIndexBelowMaxForKey(targetKey, storageLimit);
var bucket = result.storage[i] || [];
// Loop though bucket looking for matching key
for (var j = 0; j < bucket.length; j++){
// If key is found ...
if (bucket[j][0] === targetKey) {
// If the bucket has only one item, empty it completely
if (bucket.length <= 1){
result.storage[i] = [];
} else {
// else, replace the unwanted key:value pair with the popped-off last pair in the bucket
result.storage[i][j] = bucket.pop();
}
}
}
};
return result;
};
var getIndexBelowMaxForKey = function(str, max){
// Returns an index below the max. This index will return the same for any given key every time it is called.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment