Expire Cache Entries with an Injected Clock
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write a class TtlCache<V> whose entries expire ttlMs milliseconds after they were set. The constructor takes ttlMs and an optional clock, now (a function returning the time in milliseconds, Date.now by default), so tests can move time without waiting. set(key, value) stores a value under a string key and restarts its timer; get(key) returns it, or undefined once it has expired (from the moment ttlMs has passed) or was never set; has(key) says whether get would find it. Type it so values must be V, get returns V | undefined, and the clock must return a number.
Your code must pass
- Returns a value until it expires
- Forgets a value once its time is up
- Setting a key again restarts its timer
- Has no type errors
- get returns V or undefined
- Rejects values of the wrong type
- The clock must return a number