Created
July 25, 2018 21:26
-
-
Save memolog/850bfbbc1a41044f9ae9911682668cb7 to your computer and use it in GitHub Desktop.
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
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