Skip to content
jshacks.dev
Functions

Memoize with a WeakMap for object arguments

Memoize a function in JavaScript with a WeakMap when its argument is an object, so cached results are dropped with the object. Works in any Node.js.

1 min read
Summarize in AI

A Map cache holds its keys forever. When the key is an object, such as an order or a DOM node, that keeps the object alive after nothing else uses it. A WeakMap lets both go together.

JavaScript
const memoizeByObject = (fn) => {
  const cache = new WeakMap();
  return (obj) => {
    if (!cache.has(obj)) cache.set(obj, fn(obj));
    return cache.get(obj);
  };
};

let runs = 0;
const total = memoizeByObject((order) => {
  runs++;
  return order.items.reduce((sum, item) => sum + item.price, 0);
});

const order = { items: [{ price: 5 }, { price: 7 }] };
total(order);
total(order);
total({ items: [{ price: 5 }, { price: 7 }] });
console.log(total(order), runs);
Text
12 2

The second call with order is a hit. The third call has equal contents but is a different object, so it is a miss, and that is why runs ends at 2. A WeakMap holds its keys weakly, so when an order is garbage collected its cached total goes with it.

Keys must be objects, and a WeakMap cannot be iterated or cleared in one call. If the object is mutated after caching, the old result is returned, so use this for objects treated as immutable.

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.