How to Memoize a Function With Multiple Arguments
Cache results for functions with several arguments using a key function, JSON keys, nested Maps and a WeakMap, and learn which one fits each kind of input.

A memoize helper that works for one argument is a ten-line function. The moment the function takes two arguments, the question is what to use as the cache key, and the answers have different costs and different failure modes. This post shows four ways to build the key: join the arguments into a string, serialize them with JSON, nest one Map per argument, and a custom key function for objects. It gives the cases where each is wrong, with exact output on Node.js 24, and ends with a size limit and a test. It builds on the single-argument helper in what is memoization, and it applies only to pure functions, since a cache returns a stored result, and a function with side effects or hidden inputs would return a stale one.
The problem
The one-argument helper uses the argument itself as the key.
function memoize1(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) {
cache.set(arg, fn(arg));
}
return cache.get(arg);
};
}
let calls = 0;
const add = memoize1((a, b) => {
calls += 1;
return a + b;
});
console.log(add(1, 2), add(1, 3), calls);3 3 1The second call returned 3, which is wrong: 1 plus 3 is 4. The helper reads only its first argument, so add(1, 3) found the cached result for the key 1. The function ran once, and the answer for the second call was another call's answer. A memoize helper that silently ignores arguments is worse than none, so the key must include every argument that affects the result.
Option one: join the arguments
For primitives, a string key built by joining the arguments with a separator works.
function memoizeJoin(fn) {
const cache = new Map();
return (...args) => {
const key = args.join("|");
if (!cache.has(key)) {
cache.set(key, fn(...args));
}
return cache.get(key);
};
}
let joinCalls = 0;
const addJoined = memoizeJoin((a, b) => {
joinCalls += 1;
return a + b;
});
console.log(addJoined(1, 2), addJoined(1, 3), addJoined(1, 2), joinCalls);3 4 3 2Two real computations happened and one call was served from the cache. This is fast and compact, and it has two weaknesses. If an argument contains the separator, two different calls can build the same key: ("a|b", "c") and ("a", "b|c") both join to a|b|c. And join turns everything into text, so 1 and "1" collide, as do null and undefined (which become the empty string in join), arrays and objects. Use it only when the arguments are numbers or simple strings that cannot contain the separator.
Option two: JSON keys
JSON.stringify of the argument list distinguishes numbers from strings and handles nested plain data.
function memoizeJson(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (!cache.has(key)) {
cache.set(key, fn(...args));
}
return cache.get(key);
};
}
let jsonCalls = 0;
const label = memoizeJson((user, options) => {
jsonCalls += 1;
return options.upper ? user.name.toUpperCase() : user.name;
});
console.log(label({ name: "Ana" }, { upper: true }));
console.log(label({ name: "Ana" }, { upper: true }));
console.log(label({ name: "Ana" }, { upper: false }), jsonCalls);ANA
ANA
Ana 2Equal objects built separately produce the same key, so the second call hits the cache even though the objects are different instances. That is the main advantage. The weaknesses are real: property order matters, so { a: 1, b: 2 } and { b: 2, a: 1 } give different keys and only cost a cache miss, which is safe; values that JSON cannot represent are lost or changed, such as undefined, functions and symbols (dropped in objects and turned into null in arrays), NaN and Infinity (turned into null), Date objects (turned into strings), and Map and Set (turned into {}). Two calls that differ only in such a value share a key, which returns a wrong cached result:
const same = memoizeJson((x) => String(x));
console.log(same(NaN), same(Infinity), same(null));NaN NaN NaNAll three have the key [null], so the first call's answer, "NaN", was returned for all three. That is the wrong answer for two of them. Use JSON keys only when the arguments are plain data you control, and serializing a large argument has a cost that can exceed the function itself.
Option three: nested Maps
A nested Map, one level per argument, uses each argument's identity or value as a key without building a string. It treats 1 and "1" differently and works with any value as a key, including objects, by identity.
function memoizeNested(fn) {
const root = new Map();
const RESULT = Symbol("result");
return (...args) => {
let node = root;
for (const arg of args) {
if (!node.has(arg)) {
node.set(arg, new Map());
}
node = node.get(arg);
}
if (!node.has(RESULT)) {
node.set(RESULT, fn(...args));
}
return node.get(RESULT);
};
}
let nestedCalls = 0;
const pow = memoizeNested((base, exponent) => {
nestedCalls += 1;
return base ** exponent;
});
console.log(pow(2, 10), pow(2, 10), pow("2", 10), nestedCalls);1024 1024 1024 2The numeric 2 and the string "2" were separate keys, so the function ran twice, once for each. A Map key comparison uses the same-value-zero rule, which treats NaN as equal to itself and does not distinguish +0 from -0, so NaN works as a key where it would not with ===. The result is stored under a symbol, so a call with fewer arguments does not collide with a call that has more: pow(2) and pow(2, 10) are separate paths. The cost is memory, one Map per node, and by-identity matching for objects: two equal but separate objects miss the cache, which is the right behavior when identity is what you want and a surprise when it is not.
Option four: a custom key function
When you know what makes two calls equal, say so. The helper takes a function that maps the arguments to a key, and you decide what counts.
function memoizeBy(fn, keyOf) {
const cache = new Map();
return (...args) => {
const key = keyOf(...args);
if (!cache.has(key)) {
cache.set(key, fn(...args));
}
return cache.get(key);
};
}
let userCalls = 0;
const greet = memoizeBy(
(user, locale) => {
userCalls += 1;
return (locale === "fr" ? "Bonjour " : "Hello ") + user.name;
},
(user, locale) => user.id + ":" + locale
);
console.log(greet({ id: 7, name: "Ana", extra: 1 }, "fr"));
console.log(greet({ id: 7, name: "Ana", extra: 2 }, "fr"), userCalls);Bonjour Ana
Bonjour Ana 1The key function says that the user's id and the locale decide the result, so the objects differ in extra and still share an entry. This is the most precise and usually the fastest option, because it avoids serializing whole objects. The risk is yours: if the result also depends on name, and name changes for the same id, the cache returns a stale greeting. Document what the key includes, and keep it in step with the function.
Objects as keys without leaking: WeakMap
If the argument is an object and the cache should not keep it alive, use a WeakMap for that level. A nested structure can mix them: a WeakMap for object arguments and a Map for primitive ones. For a single object argument, as in the post on memoization, a plain WeakMap is enough, and entries vanish when the object is garbage collected.
function memoizeObject(fn) {
const cache = new WeakMap();
return (object) => {
if (!cache.has(object)) {
cache.set(object, fn(object));
}
return cache.get(object);
};
}
const total = memoizeObject((cart) => cart.items.reduce((sum, n) => sum + n, 0));
const cart = { items: [1, 2, 3] };
console.log(total(cart), total(cart));6 6This relies on the object not being mutated: if cart.items changes, the cached total is stale. That is the contract of memoization, and it is easiest to keep with immutable data.
Limit the size
A cache keyed by many arguments grows with the number of distinct combinations, which can be large. Add a maximum size and evict the oldest entry, using the insertion order of a Map.
function memoizeLimited(fn, keyOf, limit) {
const cache = new Map();
return (...args) => {
const key = keyOf(...args);
if (cache.has(key)) {
const value = cache.get(key);
cache.delete(key);
cache.set(key, value);
return value;
}
const value = fn(...args);
cache.set(key, value);
if (cache.size > limit) {
cache.delete(cache.keys().next().value);
}
return value;
};
}
let limitedCalls = 0;
const square = memoizeLimited((n) => (limitedCalls += 1, n * n), (n) => n, 2);
square(1);
square(2);
square(3);
square(1);
console.log(limitedCalls);4After the third call the cache held 2 and 3 and had evicted 1, so the fourth call computed 1 again, which makes four computations in total. Touching an entry on a hit moves it to the end, so recently used entries survive, which is a least-recently-used policy.
Testing a memoized function
Test that the answers are right first, and that the cache is used second. Call the function with different argument combinations that could collide, such as (1, 23) and (12, 3), and with equal values of different types, and assert the results. Then count calls to the underlying function with a spy to check that repeats are served from the cache. A test that only counts calls can pass while the answers are wrong, as the first example shows.
Where this explanation stops
This post covers synchronous functions and plain in-memory caches. It does not cover asynchronous functions, where the cache must store promises and handle failures, which is the subject of memoizing async functions, or caches shared between processes. It also does not cover libraries such as memoizee and Lodash's _.memoize, which handle many of these cases, though Lodash's default key is the first argument only, which is the problem shown at the start.


