Skip to curriculum
Jump to the editor

20.2. A cache with time to live

Medium
Topics

This question is in

20. Caches and buffers
20–30 min

An app asks the server for the same exchange rates, user profile or search results again and again. Keeping each answer for a while saves the requests, but data that never expires turns stale. A TTL cache (time to live) keeps each entry for a fixed time and then treats it as gone.

Write a TtlCache class in ttl-cache.js.

Signature

JAVASCRIPT
class TtlCache {
  constructor(defaultTtl)   // ms; a positive number or Infinity (the default)
  set(key, value, ttl)      // ttl defaults to defaultTtl; returns the cache
  get(key)                  // the value, or undefined when missing or expired
  has(key)                  // true for a live entry
  delete(key)               // true when a live entry was removed
  get size()                // the number of live entries
  prune()                   // removes expired entries; returns how many
  clear()                   // removes everything
}

Requirements

  1. defaultTtl and any ttl passed to set must be a positive number or Infinity; anything else (0, negative, NaN, a string, null) throws RangeError, and a rejected set stores nothing.
  2. set stores the value with an expiry time of now plus the ttl, and returns the cache so calls can be chained.
  3. An entry is live until now >= expiry time: still there 1 ms before its ttl, gone at the ttl.
  4. A ttl given to set overrides the default. Setting a key again replaces the value and restarts its time. Reading never extends it.
  5. get returns undefined for a missing or expired key.
  6. has is true for any live entry, also one whose value is undefined.
  7. delete removes the entry and returns true only if it was live.
  8. size counts live entries only; prune removes the expired ones and returns how many.
  9. Expired entries do not stay in memory once they have been looked at, counted or pruned.
  10. Keys can be any value and are compared like Map keys (objects by identity, NaN equals NaN, 0 equals -0, "1" differs from 1).
  11. No timers: expiry is checked when an entry is used.
  12. Each cache has its own entries and default ttl.

Examples

JAVASCRIPT
const rates = new TtlCache(60_000);         // one minute
rates.set("EUR", 1.08).set("GBP", 1.27);
rates.get("EUR");                            // 1.08
// 60 seconds later
rates.get("EUR");                            // undefined
JAVASCRIPT
const cache = new TtlCache(1000);
cache.set("token", "abc", 50);               // this entry: 50 ms
cache.set("none", undefined);
cache.has("none");                           // true
cache.get("none");                           // undefined, but it is there
JAVASCRIPT
new TtlCache(0);                             // RangeError
new TtlCache().set("k", 1).get("k");         // 1, and it never expires

Environment

  • Plain JavaScript in a browser page; the tests create new TtlCache(…) from ttl-cache.js.
  • The tests run on a virtual clock that replaces Date.now and performance.now; use either to read the time. They also count waiting timers.
  • Out of scope: a size limit (problem 20.3 adds eviction), sliding expiry, and loading values on a miss.

Hints

  1. What needs to be stored next to each value so that get can decide on its own?
  2. Why does a plain object make a poor store when keys can be objects or numbers?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…