Rate Limiter
HardUtility Functions25 min4 tests
Implement a createRateLimiter that limits how many times a function can be called within a time window.
Requirements
createRateLimiter(fn, maxCalls, windowMs)— return a rate-limited version offn- Allow at most
maxCallsinvocations perwindowMsmilliseconds - Calls exceeding the limit should be dropped (return
undefined) - The window is sliding: old calls expire after
windowMs
Example
const limited = createRateLimiter(x => x, 2, 100);
limited(1); // 1
limited(2); // 2
limited(3); // undefined (rate limited)
// After 100ms...
limited(4); // 4Hints (4)
- Track the timestamps of each call in an array.
- Before each call, remove timestamps older than
windowMs. - If the remaining count exceeds
maxCalls, drop the call. - Otherwise, record the timestamp and invoke the function.
Topics
- Utility Functions
Asked at
Stripe · Cloudflare · Amazon · Google
