UNPKG

2.47 kBJavaScriptView Raw
1/**
2 * Copyright 2017 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16/**
17 * @template T
18 * @template V
19 */
20class Multimap {
21 constructor() {
22 this._map = new Map();
23 }
24
25 /**
26 * @param {T} key
27 * @param {V} value
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 * @param {T} key
51 * @return {boolean}
52 */
53 has(key) {
54 return this._map.has(key);
55 }
56
57 /**
58 * @param {T} key
59 * @param {V} value
60 * @return {boolean}
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 * @param {T} key
78 * @param {V} value
79 * @return {boolean}
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 * @param {T} key
91 */
92 deleteAll(key) {
93 this._map.delete(key);
94 }
95
96 /**
97 * @param {T} key
98 * @return {V}
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 * @return {!Array<V>}
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 * @return {!Array<T>}
126 */
127 keysArray() {
128 return Array.from(this._map.keys());
129 }
130
131 clear() {
132 this._map.clear();
133 }
134}
135
136module.exports = Multimap;