forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdictionary.ts
86 lines (72 loc) · 1.84 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { defaultToString } from '../util';
import { ValuePair } from './models/value-pair';
export default class Dictionary<K, V> {
private table: { [key: string]: ValuePair<K, V> };
constructor(private toStrFn: (key: K) => string = defaultToString) {
this.table = {};
}
set(key: K, value: V) {
if (key != null && value != null) {
const tableKey = this.toStrFn(key);
this.table[tableKey] = new ValuePair(key, value);
return true;
}
return false;
}
get(key: K): V {
const valuePair = this.table[this.toStrFn(key)];
return valuePair == null ? undefined : valuePair.value;
}
hasKey(key: K) {
return this.table[this.toStrFn(key)] != null;
}
remove(key: K) {
if (this.hasKey(key)) {
delete this.table[this.toStrFn(key)];
return true;
}
return false;
}
values(): V[] {
return this.keyValues().map(
(valuePair: ValuePair<K, V>) => valuePair.value
);
}
keys(): K[] {
return this.keyValues().map(
(valuePair: ValuePair<K, V>) => valuePair.key
);
}
keyValues(): ValuePair<K, V>[] {
return Object.values(this.table);
}
forEach(callbackFn: (key: K, value: V) => any) {
const valuePairs = this.keyValues();
for (let i = 0; i < valuePairs.length; i++) {
const result = callbackFn(valuePairs[i].key, valuePairs[i].value);
if (result === false) {
break;
}
}
}
isEmpty() {
return this.size() === 0;
}
size() {
return Object.keys(this.table).length;
}
clear() {
this.table = {};
}
toString() {
if (this.isEmpty()) {
return '';
}
const valuePairs = this.keyValues();
let objString = `${valuePairs[0].toString()}`;
for (let i = 1; i < valuePairs.length; i++) {
objString = `${objString},${valuePairs[i].toString()}`;
}
return objString;
}
}