Created
October 25, 2018 08:59
-
-
Save moonrailgun/eaaad6065a7e2c6d9b8f887617a82ec1 to your computer and use it in GitHub Desktop.
a simple hashtable implement with js.
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
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