playwright/src/utils/multimap.ts

79 lines
1.7 KiB
TypeScript
Raw Normal View History

/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export class MultiMap<K, V> {
private _map: Map<K, Set<V>>;
constructor() {
this._map = new Map<K, Set<V>>();
}
set(key: K, value: V) {
let set = this._map.get(key);
if (!set) {
set = new Set<V>();
this._map.set(key, set);
}
set.add(value);
}
get(key: K): Set<V> {
return this._map.get(key) || new Set();
}
has(key: K): boolean {
return this._map.has(key);
}
hasValue(key: K, value: V): boolean {
const set = this._map.get(key);
if (!set)
return false;
return set.has(value);
}
get size(): number {
return this._map.size;
}
delete(key: K, value: V): boolean {
const values = this.get(key);
const result = values.delete(value);
if (!values.size)
this._map.delete(key);
return result;
}
deleteAll(key: K) {
this._map.delete(key);
}
keys(): IterableIterator<K> {
return this._map.keys();
}
values(): Iterable<V> {
const result: V[] = [];
for (const key of this.keys())
result.push(...Array.from(this.get(key)!));
return result;
}
clear() {
this._map.clear();
}
}