class Dictionary<T> {
private items: { [key: string]: T };
constructor() {
this.items = {};
}
has(key: string): boolean {
return key in this.items;
}
set(key: string, value: T): void {
this.items[key] = value;
}
get(key: string): T | undefined {
return this.items[key];
}
delete(key: string): void {
if (this.has(key)) {
delete this.items[key];
}
}
keys(): string[] {
return Object.keys(this.items);
}
values(): T[] {
return Object.values(this.items);
}
entries(): [string, T][] {
return Object.entries(this.items);
}
clear(): void {
this.items = {};
}
size(): number {
return Object.keys(this.items).length;
}
get [key: string](): T | undefined {
return this.items[key];
}
set [key: string](value: T) {
this.items[key] = value;
}
}
const dict = new Dictionary<number>();
dict.set("a", 1);
dict.set("b", 2);
dict.set("c", 3);
console.log(dict.get("a"));
console.log(dict.keys());
console.log(dict.values());
dict.delete("b");
console.log(dict.keys());
dict.clear();
console.log(dict.size());
dict["x"] = 10;
console.log(dict["x"]);
console.log(dict["d"]);