-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dictionary.ts
69 lines (57 loc) · 1.52 KB
/
Dictionary.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
export interface IDictionary<T> {
add(key: string, value: T): void;
remove(key: string): void;
containsKey(key: string): boolean;
keys(): string[];
values(): T[];
}
export class Dictionary<T> implements IDictionary<T> {
_keys: string[] = [];
_values: T[] = [];
constructor(init?: { key: string; value: T; }[],
array?: { values: T[], getKey: (o: T) => string }) {
if (init) {
for (var x = 0; x < init.length; x++) {
this.add(init[x].key, init[x].value);
}
}
if (array) {
for (var x = 0; x < array.values.length; x++) {
this.add(array.getKey(array.values[x]),
array.values[x]);
}
}
}
add(key: string, value: T) {
var i = this._keys.indexOf(key);
if (i !== -1) {
this[key] = value;
this._values[i] = value;
return;
}
this[key] = value;
this._keys.push(key);
this._values.push(value);
}
remove(key: string) {
var index = this._keys.indexOf(key, 0);
this._keys.splice(index, 1);
this._values.splice(index, 1);
delete this[key];
}
keys(): string[] {
return this._keys;
}
values(): T[] {
return this._values;
}
containsKey(key: string) {
if (typeof this[key] === "undefined") {
return false;
}
return true;
}
toLookup(): IDictionary<T> {
return this;
}
}