Skip to content
jshacks.dev
Functions

Write a memoize with a cache size limit

Write a memoize with a cache size limit in JavaScript, evicting the oldest entry from a Map once it passes the cap. Node.js 24, no libraries.

1 min read
Summarize in AI

An unbounded cache is a memory leak with a nice name. A Map remembers insertion order, so the first key is always the oldest and easy to evict.

JavaScript
const memoize = (fn, limit = 2) => {
  const cache = new Map();
  return (arg) => {
    if (cache.has(arg)) return cache.get(arg);
    const result = fn(arg);
    cache.set(arg, result);
    if (cache.size > limit) cache.delete(cache.keys().next().value);
    return result;
  };
};

let runs = 0;
const square = memoize((n) => (runs++, n * n));
square(2); square(3); square(2);
console.log(runs);
square(4); square(2);
console.log(runs);
Text
2
4

The first three calls compute 2 and 3 once each, and the third is a hit, so runs is 2. Adding 4 pushes the size to three, which evicts 2, the oldest. The next call for 2 must compute again, so runs becomes 4. Order of keys in a Map follows insertion.

This is first-in, first-out, not least recently used: a hit does not refresh the entry. Move the key to the end on every hit if you need LRU. Keys are compared by identity for objects, so it suits primitives.

Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.