Key-Value Cache With Expiry

ClassesTimersData Structures

Build an ExpiringCache class with three methods:

  • set(key, value, duration) stores the pair for duration ms and returns whether an unexpired entry for that key already existed.
  • get(key) returns the value if it is still alive, otherwise -1.
  • count() returns how many entries are currently alive.

Examples

Example 1
Input
const cache = new ExpiringCache();
cache.set(3, 30, 400);  // false
cache.set(8, 80, 100);  // false
// 250ms later
[cache.get(3), cache.get(8), cache.count()];
Output
[30, -1, 1]
Explanation
Each entry runs on its own timer. Key 8 expired at 100ms, while key 3 stays alive until 400ms, so only one entry is still counted.

Constraints

  • Keys and values are numbers
  • duration is a positive number of milliseconds

Notes

  • Setting an existing key must clear the previous timer, or the earlier timeout deletes an entry that was just refreshed.

Hints

Read the full write-up for Key-Value Cache With Expiry
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it