Implement a `createRateLimiter(maxCalls, windowMs)` that allows at most `maxCalls` within `windowMs` milliseconds. Returns `{ allow() }` which returns true/false.
Problem Statement
Implement a `createRateLimiter(maxCalls, windowMs)` that allows at most `maxCalls` within `windowMs` milliseconds. Returns `{ allow() }` which returns true/false.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Track timestamps of recent calls in an array.
š” Hint 2:
Remove timestamps older than windowMs when checking.
š” Hint 3:
Filter out old timestamps, check if count < maxCalls, and push current timestamp if allowed.
ā
Solution:
```javascript
function createRateLimiter(maxCalls, windowMs) {
const timestamps = [];
return {
allow() {
const now = Date.now();
while (timestamps.length > 0 && timestamps[0] <= now - windowMs) {
timestamps.shift();
}
if (timestamps.length < maxCalls) {
timestamps.push(now);
return true;
}
return false;
}
};
}
```