Created
March 8, 2016 20:15
-
-
Save alexellis/f96be8039c2d6097b3f6 to your computer and use it in GitHub Desktop.
HashTableInJavaScript
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
function AHashtable(size) { | |
this.table = this.init_table(size); | |
} | |
AHashtable.prototype.set = function(key, value) { | |
var self = this; | |
var index = self.jenkins_hash(key, self.table.length); | |
self.table[index] = value; | |
}; | |
AHashtable.prototype.get = function(key) { | |
var self = this; | |
var index = self.jenkins_hash(key,self.table.length); | |
return self.table[index] | |
}; | |
/** | |
* One at a time hash by Jenkins. | |
* http://www.burtleburtle.net/bob/hash/doobs.html | |
**/ | |
AHashtable.prototype.jenkins_hash = function(key, len) { | |
var hash = 0; | |
for(var i =0;i<key.length;i++) { | |
hash += key.charCodeAt(i); | |
hash += (hash << 10); | |
hash ^= (hash >> 6); | |
} | |
hash += (hash << 3); | |
hash ^= (hash >> 11); | |
hash += (hash << 15); | |
return (hash >>> 0 ) % len; | |
}; | |
AHashtable.prototype.init_table = function (size) { | |
var buckets = new Array(size); | |
return buckets; | |
} | |
var hashtable = new AHashtable(50); | |
hashtable.set("name", "Alex") | |
hashtable.set("address", "alexellis.io") | |
console.log( hashtable.get("name") ); | |
console.log( hashtable.get("address") ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment