Cache with TTL
MediumP3Coding
Implement a class TTLCache, a key-value cache whose entries expire after a time to live.
new TTLCache(defaultTtl):defaultTtlis in milliseconds.set(key, value, ttl?): store the value; it expiresttlms from now, ordefaultTtlifttlis omitted. Setting an existing key replaces its value and restarts its timer. Returns the cache.get(key): return the value, orundefinedif the key is missing or expired.has(key):trueonly for a live key.delete(key): remove the key; returnstrueif a live entry was removed.size(a getter, not a method): the number of live entries.
An entry is expired once Date.now() >= setTime + ttl. Expired entries must never be returned and must not be counted, and they should not stay in memory forever.
Example 1
- Input
- const c = new TTLCache(100); c.set('a', 1); // 50 ms later: c.get('a') -> 1 // 120 ms later: c.get('a') -> undefined
- Output
- 1, then undefined
Constraints
- ttl > 0
- Use Date.now(); no timers are required.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.