1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | class Multimap {
|
21 | constructor() {
|
22 | this._map = new Map();
|
23 | }
|
24 |
|
25 | |
26 |
|
27 |
|
28 |
|
29 | set(key, value) {
|
30 | let set = this._map.get(key);
|
31 | if (!set) {
|
32 | set = new Set();
|
33 | this._map.set(key, set);
|
34 | }
|
35 | set.add(value);
|
36 | }
|
37 |
|
38 | /**
|
39 | * @param {T} key
|
40 | * @return {!Set<V>}
|
41 | */
|
42 | get(key) {
|
43 | let result = this._map.get(key);
|
44 | if (!result)
|
45 | result = new Set();
|
46 | return result;
|
47 | }
|
48 |
|
49 | |
50 |
|
51 |
|
52 |
|
53 | has(key) {
|
54 | return this._map.has(key);
|
55 | }
|
56 |
|
57 | |
58 |
|
59 |
|
60 |
|
61 |
|
62 | hasValue(key, value) {
|
63 | const set = this._map.get(key);
|
64 | if (!set)
|
65 | return false;
|
66 | return set.has(value);
|
67 | }
|
68 |
|
69 | /**
|
70 | * @return {number}
|
71 | */
|
72 | get size() {
|
73 | return this._map.size;
|
74 | }
|
75 |
|
76 | |
77 |
|
78 |
|
79 |
|
80 |
|
81 | delete(key, value) {
|
82 | const values = this.get(key);
|
83 | const result = values.delete(value);
|
84 | if (!values.size)
|
85 | this._map.delete(key);
|
86 | return result;
|
87 | }
|
88 |
|
89 | |
90 |
|
91 |
|
92 | deleteAll(key) {
|
93 | this._map.delete(key);
|
94 | }
|
95 |
|
96 | |
97 |
|
98 |
|
99 |
|
100 | firstValue(key) {
|
101 | const set = this._map.get(key);
|
102 | if (!set)
|
103 | return null;
|
104 | return set.values().next().value;
|
105 | }
|
106 |
|
107 | /**
|
108 | * @return {T}
|
109 | */
|
110 | firstKey() {
|
111 | return this._map.keys().next().value;
|
112 | }
|
113 |
|
114 | |
115 |
|
116 |
|
117 | valuesArray() {
|
118 | const result = [];
|
119 | for (const key of this._map.keys())
|
120 | result.push(...Array.from(this._map.get(key).values()));
|
121 | return result;
|
122 | }
|
123 |
|
124 | |
125 |
|
126 |
|
127 | keysArray() {
|
128 | return Array.from(this._map.keys());
|
129 | }
|
130 |
|
131 | clear() {
|
132 | this._map.clear();
|
133 | }
|
134 | }
|
135 |
|
136 | module.exports = Multimap;
|