Count events over a sliding window: a logger rate limiter, a hit counter and a moving average
Problem
Analytics, logging and rate limiting all ask the same question: what happened in the last few seconds? Build three small classes. Times are integer seconds and arrive in non-decreasing order for each instance.
const logger = new Logger();
logger.shouldPrint(1, "foo"); // true
logger.shouldPrint(2, "bar"); // true
logger.shouldPrint(3, "foo"); // false (printed at 1)
logger.shouldPrint(11, "foo"); // true (10 seconds after 1)Ref. UR-1423 · © UIRound · uiround.com/questions/count-events-over-a-sliding-window-a-logger-rate-limiter-a-hit-counter-and-a-moving-average
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1All three keep only what the window still needs. The logger needs one number per message: when it may next be printed. The hit counter needs the hits that are still recent. The average needs the last size values.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.