Explorer
Node.js

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; } }; } ```

Rate Limiter

Hard
Implement a `createRateLimiter(maxCalls, windowMs)` that allows at most `maxCalls` within `windowMs` milliseconds. Returns `{ allow() }` which returns true/false.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[true,true,true,false]