Created
December 27, 2021 13:51
-
-
Save ProgrammingFire/3e5803c1a7d5493e8eede05ae4f2d42b to your computer and use it in GitHub Desktop.
Map Implemented In Pure TypeScript
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
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