Skip to content

Instantly share code, notes, and snippets.

@ProgrammingFire
Created December 27, 2021 13:51
Show Gist options
  • Save ProgrammingFire/3e5803c1a7d5493e8eede05ae4f2d42b to your computer and use it in GitHub Desktop.
Save ProgrammingFire/3e5803c1a7d5493e8eede05ae4f2d42b to your computer and use it in GitHub Desktop.
Map Implemented In Pure TypeScript
class MyMap<K, V> {
private map: [key: K, value: V][] = [];
set(key: K, value: V) {
const result = this.map.find(([k]) => k === key);
if (!result) {
this.map.push([key, value]);
return;
}
result[1] = value;
}
get(key: K) {
const result = this.map.find(([k]) => k === key);
if (!result) {
return null;
}
return result[1];
}
delete(key: K) {
const result = this.map.find(([k]) => k === key);
if (!result) {
return false;
}
this.map = this.map.filter((o) => o[0] !== key);
return true;
}
forEach(callback: (value: V, key: K) => void) {
this.map.forEach((o) => {
callback(o[1], o[0]);
});
}
size() {
return this.map.length;
}
clear() {
this.map = [];
}
keys() {
return this.map.map((o) => o[0]);
}
values() {
return this.map.map((o) => o[1]);
}
has(key: K) {
return !!this.map.find((o) => o[0] === key);
}
entries() {
const array: [key: K, value: V][] = [];
this.keys().forEach((k) => {
const value = this.get(k);
if (value) {
array.push([k, value]);
}
});
return array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment