class HashMap {
_storage = [];
constructor() {
}
getHash(key) {
let hashVal = 0;
for(let i = 0; i < key.length; i++) {
hashVal += key.charCodeAt(i);
}
return hashVal;
}
set(key, value) {
const hashVal = this.getHash(key);
if (!this._storage[hashVal]) {
this._storage[hashVal] = [];
this._storage[hashVal].push([key, value]);
} else {
let existingKeyIndex = -1;
for (let i = 0; i < this._storage[hashVal].length; i++) {
const existingKey = this._storage[hashVal][i][0];
if (existingKey === key) {
existingKeyIndex = i;
break;
}
}
if (existingKeyIndex >= 0) {
this._storage[hashVal][existingKeyIndex] = [key, value];
} else {
this._storage[hashVal].push([key, value]);
}
}
}
get(key) {
const hashVal = this.getHash(key);
if (!this._storage[hashVal]) {
return undefined;
}
for (const [currentKey, val] of this._storage[hashVal]) {
if (key === currentKey) {
return val;
}
}
return undefined;
}
delete(key) {
const hashVal = this.getHash(key);
if (!this._storage[hashVal]) {
return false;
}
let existingKeyIndex = -1;
for (let i = 0; i < this._storage[hashVal].length; i++) {
const existingKey = this._storage[hashVal][i][0];
if (existingKey === key) {
existingKeyIndex = i;
break;
}
}
if (existingKeyIndex >= 0) {
this._storage[hashVal].splice(existingKeyIndex, 1);
return true;
} else {
return false;
}
}
has(key) {
return !!this.get(key);
}
}
const map = new HashMap();
map.set('fart', 'brrrrrrrrnnnnnnt!');
console.log(map.get('fart'));
console.log(map.get('tarf'));
map.set('fart', 'toot!');
console.log(map.get('fart'));
console.log(map.has('fart'));
console.log(map.delete('fart'));
console.log(map.delete('tarf'));