Cache Key Generation Strategies
You'll learn: How to reliably convert function arguments of various types into unique string keys for object-based cache storage in memoization.
Why Cache Keys Matter
When you memoize a function, you need to store results in a cache object using argument values as keys. But JavaScript objects only accept strings (or Symbols) as keys. The challenge: how do you convert complex argument combinations—numbers, arrays, objects—into unique, collision-free string keys?
Common Strategies
Simple String Concatenation
For primitive arguments, join them with a delimiter:
function createKey(...args) {
return args.join('|');
}
// createKey(1, 2) → "1|2"
// createKey(1, '2') → "1|2" (collision risk!)
Problem: Type coercion can cause collisions.
JSON Serialization
Convert arguments to JSON for structured data:
function createKey(...args) {
return JSON.stringify(args);
}
// createKey({a: 1}, [2]) → '[{"a":1},[2]]'
Problem: Doesn't handle functions, undefined, Symbols, or circular references. Object property order matters.
Type-Safe Approach
Include type information:
function createKey(...args) {
return args.map(arg => `${typeof arg}:${JSON.stringify(arg)}`).join('||');
}
// createKey(1, '1') → "number:1||string:"1""
Single Argument Optimization
For single-arg functions with primitives, use the value directly as a key—objects already convert to strings naturally.
Practical Considerations
Choose your strategy based on argument types. Primitives work with simple concatenation. Structured data needs JSON. Complex cases might require custom serialization or WeakMap-based caching (for object keys).
Key Takeaway: Cache key generation must create unique strings for different argument combinations; balance simplicity with correctness based on your function's actual parameter types.