Skip to content

Instantly share code, notes, and snippets.

@ssube
Last active March 19, 2017 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssube/6aae567060d039d504975948a172a6fc to your computer and use it in GitHub Desktop.
Save ssube/6aae567060d039d504975948a172a6fc to your computer and use it in GitHub Desktop.
export class MultiMap<K, V> implements Map<K, Array<V>> {
protected _map: Map<K, Array<V>>;
constructor(entries: Array<[K, Array<V>]>) {
this._map = new Map(entries);
}
/* simple wrappers */
public clear(): void {
this._map.clear();
}
public delete(key: K): boolean {
return this._map.delete(key);
}
public forEach(callbackfn: (value: V[], key: K, map: Map<K, V[]>) => void, thisArg?: any): void {
this._map.forEach(callbackfn, thisArg);
}
public forIn(key: K, callbackfn: (value: V, key: K, map: Map<K, Array<V>>) => void, thisArg?: any): void {
this.get(key).forEach((value: V) => {
callbackfn.call(thisArg, value, key, this);
});
}
public has(key: K): boolean {
return this._map.has(key);
}
public get size(): number {
return this._map.size;
}
public [Symbol.iterator](): IterableIterator<[K, Array<V>]> {
return this._map[Symbol.iterator]();
}
public entries(): IterableIterator<[K, Array<V>]> {
return this._map.entries();
}
public keys(): IterableIterator<K> {
return this._map.keys();
}
public values(): IterableIterator<Array<V>> {
return this._map.values();
}
public [Symbol.toStringTag]: "Map";
/* end wrappers */
public get(key: K): Array<V> {
const prev = this._map.get(key);
if (prev) {
return prev;
} else {
const value: Array<V> = [];
this._map.set(key, value);
return value;
}
}
public set(key: K, values: Array<V>): this {
this._map.set(key, values);
return this;
}
public push(key: K, ...values: Array<V>): this {
this.get(key).push(...values);
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment