Rate limit to N calls per window
Client-side rate limiting keeps you inside an API's quota and stops a runaway effect from firing a hundred requests. The subtlety is that the window rolls: the limit is on any windowMs stretch ending now, not on fixed buckets. A naive counter reset every windowMs lets through twice the limit across a bucket boundary.
Implement rateLimit(fn, limit, windowMs). It returns a wrapper. On each call, count the allowed invocations that happened within the last windowMs milliseconds; if that count is below limit, invoke fn with the wrapper's arguments and its this, record the time of the invocation, and return fn's result. Otherwise drop the call — fn is not invoked — and return undefined. Invocations older than windowMs no longer count towards the limit, so a call becomes possible again as soon as the oldest recorded invocation ages out. A limit of 0 means fn is never invoked.
What it has to do
- Allow up to
limitinvocations in anywindowMsstretch. - Drop calls beyond the limit without invoking
fn, returningundefined. - Use a rolling window: an invocation stops counting once it is older than
windowMs. - Forward arguments and preserve
thisfor allowed calls, returningfn's result. - Never invoke
fnwhenlimitis0.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.