-
Notifications
You must be signed in to change notification settings - Fork 1
/
multimap.ts
43 lines (36 loc) · 903 Bytes
/
multimap.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
export class ListMultimap<K, V> {
private map = new Map<K, V[]>();
keys(): Iterable<K> {
return this.map.keys();
}
put(key: K, value: V): void {
this.get(key).push(value);
}
putAll(key: K, values: V[]): void {
this.get(key).push(...values);
}
/** Returns live collections. */
get(key: K): V[] {
if (!this.map.has(key)) {
this.map.set(key, []);
}
return this.map.get(key)!;
}
asMap(): Map<K, V[]> {
return this.map;
}
sortedCopy(): ListMultimap<K, V> {
const copy = new ListMultimap<K, V>();
const keys = Array.from(this.map.keys());
keys.sort();
for (const key of keys) {
copy.putAll(key, this.get(key));
}
return copy;
}
static identity<E>(elements: E[]): ListMultimap<E, E> {
const multimap = new ListMultimap<E, E>();
for (const e of elements) multimap.put(e, e);
return multimap;
}
}