Advertisement
kberg

Untitled

Oct 2nd, 2020
3,869
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export class Multiset<T> {
  2.     private map: Map<T, Number> = new Map();
  3.  
  4.     constructor(items: Array<T> = []) {
  5.         items.forEach((item: T) => this.add(item));
  6.     }
  7.     add(key: T, count: number = 1) : number {
  8.         var val = (this.get(key) || 0) + count;
  9.         this.map.set(key, val);
  10.         return val;
  11.     }
  12.  
  13.     get(key: T): number | undefined {
  14.         if (this.map.has(key)) {
  15.             return this.map.get(key)!.valueOf();
  16.         }
  17.         return undefined;
  18.     }
  19.  
  20.     entries(): Array<[T, number]> {
  21.         var results: Array<[T, number]> = [];
  22.         this.map.forEach((count: Number, key: T) => {
  23.             results.push([key, count.valueOf()]);
  24.         });
  25.         return results;
  26.     }
  27.  
  28.     toString(): string {
  29.         return this.map.toString();
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement