Created
November 29, 2024 11:02
-
-
Save sombreroEnPuntas/adeb20dbc1b0406f5508538be5a268ff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The Counter class tracks expiring event counts for specific labels. | |
// Events are added with a timestamp using `put`. | |
// Use `get_count` to get the count of valid events for a label. | |
// Use `get_total_count` to get the count of all valid events across labels. | |
// Events older than the expiration window are discarded automatically. | |
class Counter { | |
expirationWindow: number; | |
elements: { [key: string]: number[] } = {}; | |
constructor(expirationWindow: number) { | |
this.expirationWindow = expirationWindow; | |
} | |
// Adds a timestamp for the given label | |
put(label: string, timestamp: number): void { | |
if (!this.elements[label]) { | |
this.elements[label] = []; | |
} | |
this.elements[label].push(timestamp); | |
} | |
// Returns the count of valid timestamps for the given label | |
get_count(label: string, timestamp: number): number { | |
if (!this.elements[label]) return 0; | |
// Remove expired timestamps | |
this.elements[label] = this.elements[label].filter( | |
(time) => timestamp - time <= this.expirationWindow | |
); | |
// If no valid timestamps remain, clean up the label | |
if (this.elements[label].length === 0) { | |
delete this.elements[label]; | |
return 0; | |
} | |
return this.elements[label].length; | |
} | |
// Returns the total count of valid timestamps across all labels | |
get_total_count(timestamp: number): number { | |
let totalCount = 0; | |
for (const label of Object.keys(this.elements)) { | |
totalCount += this.get_count(label, timestamp); | |
} | |
return totalCount; | |
} | |
} | |
// Example usage | |
const counter = new Counter(3); | |
counter.put("a", 1); | |
counter.put("a", 2); | |
counter.put("b", 3); | |
counter.put("c", 4); | |
counter.put("d", 5); | |
console.log(counter.get_count("a", 4)); // Output: 2 (timestamps: [1, 2]) | |
console.log(counter.get_total_count(4)); // Output: 5 (timestamps: [1, 2, 3, 4, 5]) | |
console.log(counter.get_count("a", 6)); // Output: 0 (timestamps expired, only [b, c, d] remain) | |
console.log(counter.get_total_count(6)); // Output: 3 (timestamps: [3, 4, 5]) | |
console.log(counter.get_count("6", 6)); // Output: 0 (not a valid label) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment