Skip to content

Instantly share code, notes, and snippets.

@helderberto
Last active April 26, 2024 20:51
Show Gist options
  • Save helderberto/bbba9894c89350bccfa8b924bd55b54f to your computer and use it in GitHub Desktop.
Save helderberto/bbba9894c89350bccfa8b924bd55b54f to your computer and use it in GitHub Desktop.
// Similar to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
class Dictionary<T> {
items: { [key: string]: T };
constructor(newItems: Record<string, T>) {
this.items = newItems;
}
setItem(key: string, value: T) {
this.items[key] = value;
}
has(key: string) {
return key in this.items;
}
remove(key: string): boolean {
if (this.has(key)) {
delete this.items[key];
return true;
}
return false;
}
getItem(key: string): T | undefined {
return this.has(key) ? this.items[key] : undefined;
}
clear() {
this.items = {};
}
size(): number {
return Object.keys(this.items).length;
}
keys() {
let keys = [];
for (const k in this.items) {
if (this.has(k)) {
keys.push(k);
}
}
return keys;
}
values() {
let values = [];
for (const k in this.items) {
if (this.has(k)) {
values.push(this.items[k]);
}
}
return values;
}
getItems(): Record<string, T> {
return this.items;
}
}
interface Person {
age: number;
}
const dict = new Dictionary<Person>({
helder: {
age: 31,
},
});
dict.setItem("paula", {
age: 37,
});
console.log(dict.keys());
console.log(dict.values());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment