← All Exercises
Sliding Window Rate Limiter
advancedjavascript
Background
Rate limiters protect APIs and expensive UI actions. A sliding window avoids the burstiness of fixed windows while keeping accounting simple: store accepted timestamps and drop the ones that fall out of the window.
Problem
Implement runLimiter(limit, windowMs, events). Each event has an at timestamp and an id. An event is allowed when fewer than limit accepted events fall inside the trailing window (at - windowMs, at]. Timestamps exactly windowMs old have expired. Return the allowed and denied id lists in event order.
Input
A JSON object with limit, windowMs, and events containing at and id.
Output
A JSON object with allowed and denied arrays of event ids.
Sample tests
Sample 1
Input: {"limit":3,"windowMs":1000,"events":[{"at":0,"id":"a"},{"at":100,"id":"b"},{"at":200,"id":"c"},{"at":300,"id":"d"},{"at":1100,"id":"e"}]}Expected: {"allowed":["a","b","c","e"],"denied":["d"]}Sample 2
Input: {"limit":2,"windowMs":1000,"events":[{"at":0,"id":"a"},{"at":500,"id":"b"},{"at":1000,"id":"c"},{"at":1001,"id":"d"}]}Expected: {"allowed":["a","b","c"],"denied":["d"]}Sample 3
Input: {"limit":1,"windowMs":100,"events":[{"at":0,"id":"a"},{"at":50,"id":"b"},{"at":100,"id":"c"},{"at":150,"id":"d"}]}Expected: {"allowed":["a","c"],"denied":["b","d"]}Your solution
Learning objective
Learn sliding-window accounting, inclusive and exclusive boundary conditions, and deterministic rate-limiter testing.