Created
March 14, 2020 06:32
-
-
Save etuchscherer/855717a3266450349016ed667e1097ee to your computer and use it in GitHub Desktop.
Javascript hash map
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
/** | |
* A quick hash fn | |
* @param {string} key | |
* @param {number} limit | |
*/ | |
function hash(key, limit) { | |
const hashedKey = key.split("").reduce((acc, el) => { | |
return acc + el.charCodeAt(0); | |
}, 0); | |
return hashedKey % limit; | |
} | |
class HashMap { | |
/** | |
* Creates a new HashMap with the specified number of buckets | |
* @param size the number of buckets to create | |
*/ | |
constructor(size) { | |
this.size = size; | |
this.data = new Array(size); | |
for (let i = 0; i < this.data.length; i++) { | |
this.data[i] = new Map(); | |
} | |
} | |
/** | |
* Returns the value associated to the key, or undefined if there is none | |
* @param key | |
*/ | |
get(key) { | |
const index = hash(key, this.size); | |
return this.data[index].get(key); | |
} | |
/** | |
* Sets the value for the key in the bucket | |
* @param key | |
* @param value | |
*/ | |
set(key, value) { | |
const index = hash(key, this.size); | |
this.data[index].set(key, value); | |
} | |
/** | |
* Returns true upon successful remove | |
* @param key | |
*/ | |
delete(key) { | |
const index = hash(key, this.size); | |
return this.data[index].delete(key); | |
} | |
debug() { | |
return this.data; | |
} | |
} | |
// const dict = new HashMap(5) | |
// dict.set('eric', 1977) | |
// dict.set('andy', 1980) | |
// dict.set('max', 2013) | |
// dict.set('nathan', 1999) | |
// console.log(dict.get('eric')) | |
// console.log(dict.debug()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment