Skip to content

Instantly share code, notes, and snippets.

@memolog
Created July 25, 2018 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save memolog/850bfbbc1a41044f9ae9911682668cb7 to your computer and use it in GitHub Desktop.
Save memolog/850bfbbc1a41044f9ae9911682668cb7 to your computer and use it in GitHub Desktop.
const stringHash = require("string-hash");
module.exports = class MyHashTable {
constructor(numberOfBucket) {
this.numberOfBucket = parseInt(numberOfBucket, 10);
this.hashTable = new Array(this.numberOfBucket);
}
get(key) {
key = '' + key;
const hashTableIndex = this.getHashTableIndex(key);
const bucket = this.hashTable[hashTableIndex] || [];
const bucketLength = bucket.length;
for (let i=0; i<bucketLength; i++) {
const data = bucket[i];
if (data[0] === key) {
return data[1];
}
}
}
set(key, value) {
key = '' + key;
const hashTableIndex = this.getHashTableIndex(key);
if (!this.hashTable[hashTableIndex]) {
this.hashTable[hashTableIndex] = [];
}
this.hashTable[hashTableIndex].push([key, value]);
}
getHashTableIndex(key){
const hash = stringHash(key);
return hash % this.numberOfBucket;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment