1 /**
2   Utility class for keeping a count of items
3 */
4 module dcord.util.counter;
5 
6 import std.algorithm;
7 
8 /// Counter is a utility class to keep a count of items
9 class Counter(T) {
10   /// The total amount of items
11   uint total;
12   /// The associative array with the actual data
13   uint[T] storage;
14   
15   /// Get an element from storage
16   uint get(T v) {
17     return this.storage[v];
18   }
19 
20   /// Increment the total amount of items, and the specified item, by one 
21   void tick(T v) {
22     this.total += 1;
23     this.storage[v] += 1;
24   }
25 
26   /// Reset the count of an element
27   void reset(T v) {
28     this.total -= this.storage[v];
29     this.storage[v] = 0;
30   }
31   
32   /// Reset the count of all elements
33   void resetAll() {
34     foreach (ref k; this.storage.keys) {
35       this.reset(k);
36     }
37     this.total = 0;
38   }
39   /**
40     Find the most common item, using a schwartz sorting algorithm.
41     Params:
42       limit = the limit of items
43   */
44   auto mostCommon(uint limit) {
45     auto res = schwartzSort!(k => this.storage[k], "a > b")(this.storage.keys);
46     if (res.length > limit) {
47       return res[0..limit];
48     } else {
49       return res;
50     }
51   }
52 }