Time you can control
Handle expiry and windows without timers, so behaviour is testable.
Pass the clock in
Code that calls Date.now() inside cannot be tested at minute 9 and minute 11 of a hold. Take now as a parameter (or inject a clock) so tests can move time freely.
Expire lazily
Store expiresAt and compare it with now when you read. No background timer is needed, and nothing goes wrong if no one reads for an hour.
isLive(now: number) {
return this.state === "ACTIVE" && now < this.expiresAt;
}
Half-open intervals
Treat a time range as [start, end): it includes the start, not the end. Then 9:00–9:30 and 9:30–10:00 do not overlap, and two ranges overlap exactly when a.start < b.end and b.start < a.end.
Key takeaways
- Take now as an input.
- Store expiry times; check them on read.
- Use [start, end) for ranges.
Hands-on coding exercise
Allow each user at most `limit` actions in any `windowMs` milliseconds. The clock is passed in, so tests can move time without waiting.
class RateLimiter {
constructor(
private readonly limit: number,
private readonly windowMs: number,
private readonly now: () => number
) {}
/** true if the action is allowed (and counts it) */
allow(user: string): boolean {
throw new Error("Not implemented");
}
}
Run your solution against 4 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- Do [10, 20) and [20, 30) overlap?
- Why avoid setTimeout to expire holds?