-
Notifications
You must be signed in to change notification settings - Fork 97
/
dictionaryHelper.ts
58 lines (48 loc) · 1.8 KB
/
dictionaryHelper.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
type Dictionary<Key, Value> = { Key: Key, Value: Value }[];
export function clear(observable: any): void {
observable.setState([]);
}
export function containsKey<Key, Value>(dictionary: Dictionary<Key, Value>, identifier: Key): boolean {
return getKeyValueIndex(dictionary, identifier) !== null;
}
export function getItem<Key, Value>(dictionary: Dictionary<Key, Value>, identifier: Key, defaultValue?: Value): Value | undefined {
const index = getKeyValueIndex(dictionary, identifier);
if (index === null) {
return defaultValue;
}
return ko.unwrap(ko.unwrap(dictionary[index]).Value);
}
export function remove<Key, Value>(observable: any, identifier: Key): boolean {
let dictionary = [...observable.state];
const index = getKeyValueIndex(dictionary, identifier);
if (index === null) {
return false;
}
else {
dictionary.splice(index, 1);
observable.setState(dictionary);
return true;
}
}
export function setItem<Key, Value>(observable: any, identifier: Key, value: Value): void {
const dictionary = [...observable.state];
const index = getKeyValueIndex(dictionary, identifier);
if (index !== null) {
let keyValuePair = dictionary[index];
dictionary[index] = { Key: keyValuePair.Key, Value: value };
observable.setState(dictionary);
}
else {
dictionary.push({ Key: identifier, Value: value });
observable.setState(dictionary);
}
}
function getKeyValueIndex<Key, Value>(dictionary: Dictionary<Key, Value>, identifier: Key): number | null {
for (let index = 0; index < dictionary.length; index++) {
let keyValuePair = ko.unwrap(dictionary[index]);
if (ko.unwrap(keyValuePair.Key) == identifier) {
return index;
}
}
return null;
}