Skip to content

Checkpoint: A Bounded, Measured Cache

The Course
•
25 min study

A memo cache trades memory for repeated work: it remembers fn(key) so the next request for that key does not call fn again. Unbounded, it keeps every key it has ever seen alive, which is the retention problem from this day's third lesson. Bounded, it has to choose what to forget, and whether the bound is worth its memory is a measurement question.

Build createMemo(fn, capacity). Its get(key) returns the cached value when it has one (a hit) and otherwise calls fn (a miss). It never holds more than capacity entries, and when it must drop one it evicts the least recently used key. A hit counts as a use, so a key that keeps being read stays. stats() reports hits, misses, evictions and the peak number of entries.

Then measure, as the measurement lesson recommends, by counting rather than timing: run one workload at capacities 1, 2 and 3 and compare how often fn is called. Counts are exact and the same on every machine, so the checkpoint can check them.

Predict, run, and explain

Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.

Predict, then run JavaScript
const order = new Map([
  ["a", 1],
  ["b", 2]
]);

order.set("a", 10);
console.log([...order.keys()].join(","));

order.delete("a");
order.set("a", 10);
console.log([...order.keys()].join(","));
console.log(order.keys().next().value);
Check your prediction
Text
a,b
b,a
b

Setting an existing key changes its value but not its position. Deleting and setting it again moves it to the end, so the first key in iteration order is always the one used longest ago, if every use is written this way.

Acceptance cases before you code

Write a small test plan before implementing chunked calculation and scheduling. These cases extend the brief; they are not a second worked solution. Predict the expected behavior independently, then test through the public function. A good ordinary example and a good boundary example should catch different possible mistakes.

Case to tryWhat your result should demonstrate
Capacity 1 on the workloadEvery request misses, because each new page pushes out the last
Capacity 2home survives between pages because each hit refreshes it: 6 calls (8 without the refresh)
Capacity 3No fewer calls than capacity 2: the extra slot costs memory and buys nothing here
Any capacitypeak never exceeds the capacity, and the rendered output matches no cache at all
Capacity 0RangeError when the memo is created

After the core task passes, deliberately break one rule and identify the case that notices it. Restore the implementation and explain the failure in terms of the contract, not the number of assertions. If a case requires a concept you have not recalled, revisit the relevant lesson before opening the solution.

Your turn

Exercise

Checkpoint: a bounded memo

Finish createMemo so every acceptance case passes. The workload and the reporting loop are supplied. Print:

Text
capacity 1: calls 10, hits 0, evictions 9, peak 1, same output true
capacity 2: calls 6, hits 4, evictions 4, peak 2, same output true
capacity 3: calls 6, hits 4, evictions 3, peak 3, same output true
RangeError: capacity must be a positive integer
Your workspace JavaScript
function createMemo(fn, capacity) {
  // First draft: remembers everything and never evicts. Add the capacity
  // check, eviction of the least recently used key, and the stats.
  const cache = new Map();
  const stats = { hits: 0, misses: 0, evictions: 0, peak: 0 };

  function get(key) {
    if (cache.has(key)) {
      stats.hits += 1;
      return cache.get(key);
    }
    stats.misses += 1;
    const value = fn(key);
    cache.set(key, value);
    return value;
  }

  return { get, stats: () => ({ ...stats, size: cache.size }) };
}

// Workload: "home" is requested between every other page.
const requests = ["home", "a", "home", "b", "home", "c", "home", "a", "home", "d"];

for (const capacity of [1, 2, 3]) {
  let calls = 0;
  const memo = createMemo(page => {
    calls += 1;
    return `<${page}>`;
  }, capacity);
  const rendered = requests.map(memo.get).join("");
  const s = memo.stats();
  console.log(
    `capacity ${capacity}: calls ${calls}, hits ${s.hits}, evictions ${s.evictions}, peak ${s.peak}, same output ${rendered === requests.map(p => `<${p}>`).join("")}`
  );
}

try {
  createMemo(x => x, 0);
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}
Hint 1: the idea

Use the Map's insertion order as the recency order, as the warm-up showed. Two places must keep it correct: a miss adds a new newest key, and a hit must also move its key to the end. Eviction is then always "delete the first key".

Hint 2: a first step

Add the capacity check, then after cache.set on a miss, evict cache.keys().next().value when cache.size > capacity, counting evictions and updating peak. Run it: capacity 1 should now show 10 calls. Capacity 2 will still be wrong until hits refresh their key.

Show one solution
JavaScript
function createMemo(fn, capacity) {
  if (!Number.isInteger(capacity) || capacity < 1) {
    throw new RangeError("capacity must be a positive integer");
  }
  const cache = new Map();
  const stats = { hits: 0, misses: 0, evictions: 0, peak: 0 };

  function get(key) {
    if (cache.has(key)) {
      stats.hits += 1;
      const value = cache.get(key);
      cache.delete(key); // refresh: a read makes this key the newest
      cache.set(key, value);
      return value;
    }
    stats.misses += 1;
    const value = fn(key);
    cache.set(key, value);
    if (cache.size > capacity) {
      cache.delete(cache.keys().next().value);
      stats.evictions += 1;
    }
    stats.peak = Math.max(stats.peak, cache.size);
    return value;
  }

  return { get, stats: () => ({ ...stats, size: cache.size }) };
}

// Workload: "home" is requested between every other page.
const requests = ["home", "a", "home", "b", "home", "c", "home", "a", "home", "d"];

for (const capacity of [1, 2, 3]) {
  let calls = 0;
  const memo = createMemo(page => {
    calls += 1;
    return `<${page}>`;
  }, capacity);
  const rendered = requests.map(memo.get).join("");
  const s = memo.stats();
  console.log(
    `capacity ${capacity}: calls ${calls}, hits ${s.hits}, evictions ${s.evictions}, peak ${s.peak}, same output ${rendered === requests.map(p => `<${p}>`).join("")}`
  );
}

try {
  createMemo(x => x, 0);
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}
Text
capacity 1: calls 10, hits 0, evictions 9, peak 1, same output true
capacity 2: calls 6, hits 4, evictions 4, peak 2, same output true
capacity 3: calls 6, hits 4, evictions 3, peak 3, same output true
RangeError: capacity must be a positive integer

On a miss, the new key goes to the end and the first key, the least recently used, is evicted once the size passes capacity. peak is updated after that, so it can never exceed the bound. On a hit, delete then set moves the key to the end. That is why, at capacity 2, home is never the oldest entry when a new page arrives, so fn runs only for the first home and for each other page not currently held: 6 calls. Without that refresh, home is evicted twice and the count rises to 8. Capacity 3 makes the same 6 calls with one more entry held, so on this workload the measurement says capacity 2 is the better choice. same output checks that caching never changed what was rendered, which is the correctness check to do before reading any count.

Change it and test it

Remove the two lines that refresh a key on a hit and run again. Which capacity's numbers change, and why does home now get evicted? Then design a workload where capacity 3 does beat capacity 2, and predict its counts before running it.

Was this article helpful?

Your response is saved on this device.