-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.ts
46 lines (35 loc) · 995 Bytes
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
export interface Dictionary<T> {
readonly size: number;
clear(): void;
delete(key: string | number): boolean;
get(key: string | number): T | undefined;
has(key: string | number): boolean;
set(key: string | number, value: T): this;
}
export class Dictionary<T> {
// Dictionary key will always be set as a string.
private table: { [key: string]: T } = {};
readonly size: number = 0;
clear() {
this.table = {};
}
delete(key: string | number) {
delete this.table[key.toString()];
return true;
}
get(key: string | number) {
return this.table[key.toString()];
}
has(key: string | number) {
return this.table[key.toString()] !== undefined;
}
set(key: string | number, value: T) {
this.table[key.toString()] = value;
return this;
}
}
const dictionary = new Dictionary<number | string>();
dictionary.set(1, 1);
dictionary.set("foo", "bar");
console.log(dictionary.set(1, 1).get(1));
// console.log(JSON.stringify(dictionary));