CodePark/ problems / Cache with expiring keys
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Timers and scheduling

Cache with expiring keys

mediumabout 25 minutes in an interview

Implement a class TimeLimitedCache<K, V>: a key/value store where each entry expires on its own timer. An entry is live until its time runs out.

Methods:

  • set(key, value, duration) stores value under key and gives it duration ms to live, counted from now. If key is already there, the new value and the new timer both replace the old ones. It returns true when it replaced a live entry and false otherwise.
  • get(key) gives back the live value for key. A missing or expired key gives undefined.
  • delete(key) removes key. It returns true when a live entry was removed and false otherwise.
  • count() gives the number of live entries at this moment.

Timing: an entry set at time t with duration d is live up to, but not including, t + d. At exactly t + d it has expired.

Input: c.set(1, 'a', 100); // at 0 ms c.get(1) at 99 ms c.get(1) at 100 ms Output: 'a', then undefined
Input: c.set(1, 'a', 100) at 0; c.set(1, 'b', 100) at 50; c.get(1) at 120 Output: false, true, 'b'The second set restarted the lifetime, so the key lives until 150.