Last active
May 20, 2023 09:48
-
-
Save mostafa8026/87e8849c2eb64190446a61371f99f691 to your computer and use it in GitHub Desktop.
A TypeScript class for tracking the number of requests within a sliding time window
This file contains 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
class WindowCounter { | |
private windowSize: number; // Window size in seconds | |
private counter: Map<number, number>; // Map to store request counts | |
private timer: any; // Timer reference | |
constructor(windowSize: number) { | |
this.windowSize = windowSize; | |
this.counter = new Map(); | |
this.timer = null; | |
} | |
public start(): void { | |
// Clear the existing counter and start the timer | |
this.counter.clear(); | |
this.timer = setInterval(this.slideWindow, 1000); // Slide the window every second | |
} | |
public stop(): void { | |
// Stop the timer | |
if (this.timer) { | |
clearInterval(this.timer); | |
this.timer = null; | |
} | |
} | |
public addRequest(): void { | |
// Add a request count to the current second's index | |
const currentSecond = Math.floor(Date.now() / 1000); | |
const count = this.counter.get(currentSecond) || 0; | |
this.counter.set(currentSecond, count + 1); | |
} | |
private slideWindow = (): void => { | |
// Remove the oldest second's count from the counter map | |
const currentSecond = Math.floor(Date.now() / 1000); | |
const oldestSecond = currentSecond - this.windowSize; | |
this.counter.delete(oldestSecond); | |
}; | |
public getRequestCount(): number { | |
// Calculate and return the total request count within the window | |
let totalCount = 0; | |
for (const count of this.counter.values()) { | |
totalCount += count; | |
} | |
return totalCount; | |
} | |
} | |
const counter = new WindowCounter(10); // 10-second window | |
counter.start(); | |
// Simulate requests | |
counter.addRequest(); | |
counter.addRequest(); | |
counter.addRequest(); | |
setTimeout(() => { | |
counter.addRequest(); | |
}, 5000); // Add a request after 5 seconds | |
setTimeout(() => { | |
counter.addRequest(); | |
counter.stop(); | |
console.log(`Total requests in the last 10 seconds: ${counter.getRequestCount()}`); | |
}, 11000); // Stop the counter after 11 seconds and get the request count | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment