UNPKG

1.93 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
17class 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
95module.exports = Multimap;