Skip to content

Instantly share code, notes, and snippets.

@moonrailgun
Created October 25, 2018 08:59
Show Gist options
  • Save moonrailgun/eaaad6065a7e2c6d9b8f887617a82ec1 to your computer and use it in GitHub Desktop.
Save moonrailgun/eaaad6065a7e2c6d9b8f887617a82ec1 to your computer and use it in GitHub Desktop.
a simple hashtable implement with js.
class HashTable {
constructor (size = 16) {
this.bucket = [];
this.bucketSize = size;
}
getHash(str) {
try {
return str.split('').map(function(c) {
return c.charCodeAt();
}).reduce(function (a, b) {
return a + b;
});
}catch (err) {
return 0;
}
}
set(key, value) {
let hash = this.getHash(key);
let index = hash % this.bucketSize;
if(this.bucket[index] === undefined) {
this.bucket[index] = [[key, value]];
}else {
for (let pair of this.bucket[index]) {
if(pair[0] === key) {
pair[1] = value
return;
}
}
this.bucket[index].push([key, value]);
}
}
get(key) {
let hash = this.getHash(key);
let index = hash % this.bucketSize;
if(this.bucket[index] === undefined) {
return undefined
}else {
for (let pair of this.bucket[index]) {
if(pair[0] === key) {
return pair[1]
}
}
return undefined;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment