Skip to content
Onsite

Cache with TTL

MediumP3Coding

Implement a class TTLCache, a key-value cache whose entries expire after a time to live.

  • new TTLCache(defaultTtl): defaultTtl is in milliseconds.
  • set(key, value, ttl?): store the value; it expires ttl ms from now, or defaultTtl if ttl is omitted. Setting an existing key replaces its value and restarts its timer. Returns the cache.
  • get(key): return the value, or undefined if the key is missing or expired.
  • has(key): true only for a live key.
  • delete(key): remove the key; returns true if 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

Run checks the 3 visible tests, Submit all 9.