-
Notifications
You must be signed in to change notification settings - Fork 0
/
key-value-counter.ts
68 lines (57 loc) · 1.57 KB
/
key-value-counter.ts
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
export interface SimpleWrapper {
key: string;
count: number;
}
export class KeyValueCounter {
private readonly data: { [key: string]: number } = {};
private results: SimpleWrapper[] = [];
private processed = false;
public add(item: string): void {
if (item in this.data) {
this.data[item]++;
} else {
this.data[item] = 1;
}
if (this.processed) {
this.processed = false;
}
}
public addAll(items: readonly string[]): void {
items.forEach((item) => {
if (item in this.data) {
this.data[item]++;
} else {
this.data[item] = 1;
}
});
if (this.processed) {
this.processed = false;
}
}
public getAll(): readonly SimpleWrapper[] {
if (!this.processed) {
this.process();
}
return this.results;
}
public getTopN(count: number): readonly SimpleWrapper[] {
if (!this.processed) {
this.process();
}
return this.results.slice(0, count);
}
public get length(): number {
return this.getAll().length;
}
/**
* @deprecated use {@link length} instead
*/
public getCount(): number {
return this.getAll().length;
}
private process(): void {
this.results = Object.entries(this.data).map(([key, count]) => ({key, count}));
this.results.sort((a, b) => b.count - a.count);
this.processed = true;
}
}