2020-02-01 05:10:50 +01:00
|
|
|
export class Dict<V> {
|
2020-02-03 07:05:56 +01:00
|
|
|
private _items: Map<string, V> = new Map();
|
2019-02-08 11:56:33 +01:00
|
|
|
|
2020-02-01 05:10:50 +01:00
|
|
|
get(key: string): V | undefined {
|
2020-02-03 07:05:56 +01:00
|
|
|
return this._items.get(this._munge(key));
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
2020-02-03 07:18:13 +01:00
|
|
|
set(key: string, value: V): Dict<V> {
|
2020-02-03 07:05:56 +01:00
|
|
|
this._items.set(this._munge(key), value);
|
2020-02-03 07:18:13 +01:00
|
|
|
return this;
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
2020-02-01 05:10:50 +01:00
|
|
|
has(key: string): boolean {
|
2020-02-03 07:05:56 +01:00
|
|
|
return this._items.has(this._munge(key));
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
2020-02-01 05:10:50 +01:00
|
|
|
del(key: string): void {
|
2020-02-03 07:05:56 +01:00
|
|
|
this._items.delete(this._munge(key));
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
2020-02-01 05:10:50 +01:00
|
|
|
keys(): string[] {
|
2020-02-03 07:05:56 +01:00
|
|
|
return [...this._items.keys()];
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
values(): V[] {
|
2020-02-03 07:05:56 +01:00
|
|
|
return [...this._items.values()];
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
2020-02-01 05:10:50 +01:00
|
|
|
items(): [string, V][] {
|
2020-02-03 07:05:56 +01:00
|
|
|
return [...this._items];
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
num_items(): number {
|
2020-02-03 07:05:56 +01:00
|
|
|
return this._items.size;
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
is_empty(): boolean {
|
2020-02-03 07:05:56 +01:00
|
|
|
return this._items.size === 0;
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
2020-02-01 05:10:50 +01:00
|
|
|
each(f: (v: V, k?: string) => void): void {
|
2020-02-03 07:05:56 +01:00
|
|
|
this._items.forEach(f);
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
|
|
|
|
2019-03-25 15:55:39 +01:00
|
|
|
clear(): void {
|
2020-02-03 07:05:56 +01:00
|
|
|
this._items.clear();
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|
2019-03-25 15:55:39 +01:00
|
|
|
|
2019-12-26 15:34:17 +01:00
|
|
|
// Convert keys to strings and handle undefined.
|
2020-02-01 05:10:50 +01:00
|
|
|
private _munge(key: string): string | undefined {
|
2019-03-25 15:55:39 +01:00
|
|
|
if (key === undefined) {
|
|
|
|
blueslip.error("Tried to call a Dict method with an undefined key.");
|
|
|
|
return undefined;
|
|
|
|
}
|
2020-02-01 05:10:50 +01:00
|
|
|
|
|
|
|
if (typeof key !== 'string') {
|
|
|
|
blueslip.error("Tried to call a Dict method with a non-string.");
|
|
|
|
key = (key as object).toString();
|
|
|
|
}
|
|
|
|
|
2020-02-03 07:05:56 +01:00
|
|
|
return key;
|
2019-03-25 15:55:39 +01:00
|
|
|
}
|
2019-02-08 11:56:33 +01:00
|
|
|
}
|