Deviopath › Node.js

TTL Cache

Medium · Caching

Servers often cache results in memory for a short time (a TTL, "time to live"). Implement the TtlCache class. Time is passed in as now (ms) instead of reading the clock, so it is easy to test.

- set(key, value, ttlMs, now) stores the value until now + ttlMs. Setting an existing key replaces its value AND its expiry.

- An entry is expired when now >= expiresAt. Expired entries behave as if they do not exist.

- get(key, now) returns the value, or undefined if missing/expired. Values can be anything, including 0 and "".

- delete(key, now) removes the key and returns true if a live entry was removed, false otherwise (like Map.prototype.delete).

- size(now) returns the number of live entries.

The driver runCache(ops) is already written. It runs the operations and collects the results of get (turning undefined into null), delete and size.

Next: Content Negotiation