Skip to content

Instantly share code, notes, and snippets.

@tdubs42
Created February 19, 2024 06:43
Show Gist options
  • Save tdubs42/3a892fd1614a95f43709c9384c4dc978 to your computer and use it in GitHub Desktop.
Save tdubs42/3a892fd1614a95f43709c9384c4dc978 to your computer and use it in GitHub Desktop.
Hash Map Class - JavaScript
const LinkedList = require('./LinkedList');
const Node = require('./Node');
class HashMap {
constructor(size = 0) {
this.hashmap = new Array(size)
.fill(null)
.map(() => new LinkedList());
}
hash(key) {
let hashCode = 0;
for (let i = 0; i < key.length; i++) {
hashCode += hashCode + key.charCodeAt(i);
}
return hashCode % this.hashmap.length;
}
assign(key, value) {
const arrayIndex = this.hash(key);
const linkedList = this.hashmap[arrayIndex];
console.log(`Storing ${value} at index ${arrayIndex}`);
if (linkedList.head === null) {
linkedList.addToHead({ key, value });
return;
}
let current = linkedList.head;
while (current) {
if (current.data.key === key) {
current.data = { key, value };
}
if (!current.next) {
current.next = new Node({ key, value });
break;
}
current = current.next;
}
}
retrieve(key) {
const arrayIndex = this.hash(key);
let current = this.hashmap[arrayIndex].head;
while (current) {
if (current.data.key === key) {
console.log(`\nRetrieving ${current.data.value} from index ${arrayIndex}`);
return current.data.value;
}
current = current.next;
}
return null;
}
}
module.exports = HashMap;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment