-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFrequencyMap.ts
More file actions
74 lines (68 loc) · 1.97 KB
/
FrequencyMap.ts
File metadata and controls
74 lines (68 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* FrequencyMap extends the built-in Map to keep track of frequency counts for values.
* It overrides the set() and delete() methods to enforce using increment() and decrement() instead.
*/
export class FrequencyMap<T> extends Map<T, number> {
/**
* Constructor allows passing in an iterable to initialize the map.
* Calls increment() for each element.
*/
constructor(iterable?: Iterable<T>) {
super();
if (iterable) {
for (const item of iterable) {
this.increment(item);
}
}
}
static ERROR =
"This class uses increment and decrement methods. If you really want to use the parent method (why tho?), use Map.prototype.set() or Map.prototype.delete() instead.";
/**
* Overrides Map set() to throw an error.
* @override
*/
override set(key: T, value: number): never {
throw new Error(FrequencyMap.ERROR);
}
/**
* Overrides Map delete() to throw an error.
* @override
*/
override delete(key: T): never {
throw new Error(FrequencyMap.ERROR);
}
/**
* Increments the value for the given element by 1.
* Initializes to 0 if not present.
*/
increment(element: T): this {
const count = this.get(element) || 0;
super.set(element, count + 1);
return this;
}
/**
* Decrements the value for the given element by 1.
* Deletes the key if decremented to 0.
* Returns true if deleted, false otherwise.
*/
decrement(value: T): boolean {
const count = this.get(value);
if (count === 1) {
return super.delete(value);
} else if (count) {
super.set(value, count - 1);
}
return false;
}
/**
* Returns an array of the keys sorted by frequency count.
* @param ascending - Sort ascending if true, descending if false.
*/
sorted(ascending = true): ReadonlyArray<T> {
const entries = [...this.entries()];
entries.sort((a, b) => {
return ascending ? a[1] - b[1] : b[1] - a[1];
});
return entries.map((entry) => entry[0]);
}
}