1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | class Multimap {
|
18 | constructor() {
|
19 | this._map = new Map();
|
20 | }
|
21 |
|
22 | set(key, value) {
|
23 | let set = this._map.get(key);
|
24 | if (!set) {
|
25 | set = new Set();
|
26 | this._map.set(key, set);
|
27 | }
|
28 | set.add(value);
|
29 | }
|
30 |
|
31 | get(key) {
|
32 | let result = this._map.get(key);
|
33 | if (!result)
|
34 | result = new Set();
|
35 | return result;
|
36 | }
|
37 |
|
38 | has(key) {
|
39 | return this._map.has(key);
|
40 | }
|
41 |
|
42 | hasValue(key, value) {
|
43 | const set = this._map.get(key);
|
44 | if (!set)
|
45 | return false;
|
46 | return set.has(value);
|
47 | }
|
48 |
|
49 | /**
|
50 | * @return {number}
|
51 | */
|
52 | get size() {
|
53 | return this._map.size;
|
54 | }
|
55 |
|
56 | delete(key, value) {
|
57 | const values = this.get(key);
|
58 | const result = values.delete(value);
|
59 | if (!values.size)
|
60 | this._map.delete(key);
|
61 | return result;
|
62 | }
|
63 |
|
64 | deleteAll(key) {
|
65 | this._map.delete(key);
|
66 | }
|
67 |
|
68 | firstValue(key) {
|
69 | const set = this._map.get(key);
|
70 | if (!set)
|
71 | return null;
|
72 | return set.values().next().value;
|
73 | }
|
74 |
|
75 | firstKey() {
|
76 | return this._map.keys().next().value;
|
77 | }
|
78 |
|
79 | valuesArray() {
|
80 | const result = [];
|
81 | for (const key of this._map.keys())
|
82 | result.push(...Array.from(this._map.get(key).values()));
|
83 | return result;
|
84 | }
|
85 |
|
86 | keysArray() {
|
87 | return Array.from(this._map.keys());
|
88 | }
|
89 |
|
90 | clear() {
|
91 | this._map.clear();
|
92 | }
|
93 | }
|
94 |
|
95 | module.exports = Multimap;
|