Skip to content

Instantly share code, notes, and snippets.

@d3vild06
Last active February 13, 2017 19:03
Show Gist options
  • Save d3vild06/783ec5bbb8b8e795d71d6567f1165532 to your computer and use it in GitHub Desktop.
Save d3vild06/783ec5bbb8b8e795d71d6567f1165532 to your computer and use it in GitHub Desktop.
Hash Map Implementation
class HashMap {
constructor(capacity) {
this.length = 0;
this._slots = [];
this.capacity = capacity || 8;
this.deleted = 0;
};
set(key, value) {
const loadRatio = (this.length + this.deleted + 1) / this.capacity;
if (loadRatio > this.MAX_LOAD_RATIO) {
this._resize(this.capacity * this.SIZE_RATIO)
}
const index = this._findSlot(key);
this._slots[index] = {
key,
value,
deleted: false
}
this.length++;
}
get(key) {
const index = this._findSlot(key);
if (index === undefined) {
throw new Error('key error');
}
return this._slots[index].value;
}
remove(key) {
const index = this._findSlot(key);
const slot = this._slots[index];
if (slot === undefined) {
throw new Error('key error: not found');
}
slot.deleted = true; // soft delete
this.length--;
this.deleted++;
}
_hashString(string) {
var hash = 5381;
for (var i=0; i<string.length; i++) {
hash = (hash << 5) + hash + string.charCodeAt(i);
hash = hash & hash;
}
return hash >>> 0;
}
_resize(size) {
let oldSlots = this._slots;
this.length = 0;
this.capacity = size;
this.deleted = 0;
this._slots = [];
for (let i = 0; i < oldSlots.length; i += 1) {
const slot = oldSlots[i];
if (slot !== undefined) {
this.set(slot.key, slot.value);
}
}
}
_findSlot(key) {
const hash = this._hashString(key);
const start = hash % this.capacity;
for (let i = start; i < start + this.capacity; i += 1) {
let index = i % this.capacity;
let slot = this._slots[index];
if (slot === undefined || (slot.key == key && !slot.deleted) ) {
return index;
}
}
}
}
let map = new HashMap(7);
map.MAX_LOAD_RATIO = 0.9;
map.SIZE_RATIO = 3;
map.set('New York', 'Albany');
map.set('Massachussetts', 'Boston');
map.set('Florida', 'Tallahassee');
console.log(map);
console.log('Capital of Florida is: ', map.get('Florida'));
console.log('Capital of Massachussetts is: ', map.get('Massachussetts'));
console.log('Removing New York.....');
map.remove('New York');
console.log('Map updated view......');
console.log(map);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment