Hard
This question is a daily question and will count towards your daily streak.
In a real-time chat application, you need to implement rate limiting for message sending. What will be the maximum number of messages a user can send in any 5-second window using this implementation?
1class RateLimiter {2 #queue = [];3 #windowSize;4 #maxRequests;56 constructor(windowSize, maxRequests) {7 this.#windowSize = windowSize;8 this.#maxRequests = maxRequests;9 }1011 async checkLimit() {12 const now = Date.now();13 this.#cleanOldRequests(now);1415 if (this.#queue.length >= this.#maxRequests) {16 const oldestRequest = this.#queue[0];17 const waitTime = oldestRequest + this.#windowSize - now;18 if (waitTime > 0) {19 await new Promise(resolve => setTimeout(resolve, waitTime));20 return this.checkLimit();21 }22 }2324 this.#queue.push(now);25 return true;26 }2728 #cleanOldRequests(now) {29 const threshold = now - this.#windowSize;30 while (this.#queue.length && this.#queue[0] <= threshold) {31 this.#queue.shift();32 }33 }34}3536const limiter = new RateLimiter(5000, 3);3738async function sendMessage(msg) {39 await limiter.checkLimit();40 console.log(`Sent: ${msg} at ${Date.now()}`);41}4243// Testing the rate limiter44(async () => {45 for (let i = 1; i <= 5; i++) {46 sendMessage(`Message ${i}`).catch(console.error);47 }48})();