memoize()
memoize<
Args,Result>(fn,keyResolver?): MemoizedFunction<Args,Result>
memoize<
Args,Result>(fn,options?): MemoizedFunction<Args,Result>
Creates a memoized version of a function that caches results based on arguments.
By default, uses the first argument as the cache key (like lodash/es-toolkit).
For multi-argument caching or complex keys, provide a custom keyResolver.
Type Parametersβ
Args: Args extends unknown[]β
The argument types of the function.
Result: Resultβ
The return type of the function.
Parametersβ
Overload 1:
fn: (...args) => Resultβ
The function to memoize.
keyResolver?: (...args) => unknownβ
Optional function to generate cache keys (for first overload).
Overload 2:
fn: (...args) => Resultβ
The function to memoize.
options?: MemoizeOptions<Args, Result>β
Memoization options (for second overload).
Returns: MemoizedFunction<Args, Result>β
The memoized function with clear(), delete() methods and cache property.
Sinceβ
2.0.0
Performanceβ
Uses first argument as cache key by default (no serialization). Single Map.get() lookup on cache hit. Custom cache allows LRU/TTL strategies.
Also known asβ
memo (Radashi) Β· memoize (Lodash, es-toolkit, Modern Dash) Β· memoizeWith (Ramda) Β· β (Remeda, Effect, Antfu)
Exampleβ
const square = memoize((n: number) => n * n);
square(5); // 25 (computed)
square(5); // 25 (cached)
square.delete(5); // Invalidate specific entry
square.clear(); // Clear all
// With custom key resolver for multi-arg functions
const add = memoize(
(a: number, b: number) => a + b,
(a, b) => `${a},${b}`
);
// With custom cache (e.g., LRU)
const fetchUser = memoize(
(id: string) => fetch(`/api/users/${id}`),
{ cache: new LRUCache(100) }
);
How it works?β
Caches function results based on arguments. Same arguments return cached result β different arguments compute and cache new result.
Cache Flowβ
Methodsβ
Use Casesβ
Cache expensive calculations πβ
Store results of expensive operations to avoid redundant computation. Essential for performance optimization and reducing computational overhead.
const factorial = memoize((n) => {
if (n <= 1) return 1;
return n * factorial(n - 1);
});
factorial(5); // Computed
factorial(5); // Cached result returned instantly
Cache API responses πβ
Store API responses to avoid duplicate requests. Critical for API optimization and reducing network traffic.
const fetchUser = memoize(async (id) => {
const res = await fetch(`/api/users/${id}`);
return res.json();
});
// Second call returns same promise/result without network request
await fetchUser("123");
await fetchUser("123");
Cache DOM queriesβ
Store DOM element references to avoid repeated queries. Essential for DOM manipulation and performance optimization.
const getElement = memoize((selector) => document.querySelector(selector));
// Only queries DOM once per selector
const btn = getElement("#submit-btn");
const btnAgain = getElement("#submit-btn"); // Cached
Cache credit score calculations for loan processingβ
Cache expensive credit score calculations to speed up loan application workflows. Critical for banking systems processing high volumes of loan applications.
// Credit score calculation is expensive (calls multiple APIs, runs ML models)
const calculateCreditScore = memoize(async (applicantId: string) => {
// Aggregate data from multiple sources
const [paymentHistory, debtRatio, creditAge, inquiries] = await Promise.all([
creditBureau.getPaymentHistory(applicantId),
creditBureau.getDebtRatio(applicantId),
creditBureau.getCreditAge(applicantId),
creditBureau.getRecentInquiries(applicantId),
]);
// Complex scoring algorithm
let score = 300;
score += paymentHistory.onTimeRate * 200;
score += (1 - debtRatio) * 150;
score += Math.min(creditAge / 10, 1) * 100;
score -= inquiries * 5;
return Math.round(Math.min(Math.max(score, 300), 850));
});
// Same applicant checking multiple loan products - reuses cached score
const autoLoanEligibility = await checkEligibility(
await calculateCreditScore("APP-12345"),
"auto"
);
const mortgageEligibility = await checkEligibility(
await calculateCreditScore("APP-12345"), // Cache hit!
"mortgage"
);
Cache parsed templates or markdownβ
Avoid re-parsing the same template or markdown content on every render. Important for SSR, documentation sites, and any repeated content transformation.
const parseMarkdown = memoize((source: string) => {
// Expensive: tokenize, parse AST, render HTML
return markdownCompiler.render(source);
});
// Same content parsed once, cached for subsequent renders
const html1 = parseMarkdown(readmeContent); // Parsed
const html2 = parseMarkdown(readmeContent); // Cache hit
MemoizeCache<K, V>β
A cache interface for memoization, compatible with Map and custom implementations (LRU, TTL, etc.).
Sinceβ
2.0.0
Type Parametersβ
K: Kβ
The key type.
V: Vβ
The value type.
Propertiesβ
size: numberβ
The number of entries in the cache.
Methodsβ
set()β
Stores a value in the cache.
key:
K
value:V
Returns:void
get()β
Retrieves a value from the cache, or undefined if not found.
key:
K
Returns:V | undefined
has()β
Checks if a key exists in the cache.
key:
K
Returns:boolean
delete()β
Removes a key from the cache.
key:
K
Returns:boolean | void
clear()β
Clears all entries from the cache.
Returnsβ
void
MemoizeOptions<Args, Result>β
Options for the memoize function.
Sinceβ
2.0.0
Type Parametersβ
Args: Args extends unknown[]β
The argument types of the function.
Result: Resultβ
The return type of the function.
Propertiesβ
cache?: MemoizeCache<unknown, Result>β
Custom cache implementation.
keyResolver()?: (...args) => unknownβ
Function to generate cache keys.
args:
...Args
Returns:unknown
MemoizedFunction<Args, Result>β
MemoizedFunction<
Args,Result> = (...args) =>Result&object
A memoized function with cache management methods.
Type Declarationβ
clear(): () => voidβ
Clears all cached results.
Returns: voidβ
delete(): (...args) => booleanβ
Removes a specific cached result.
args:
...Args
Returns:boolean
cache: MemoizeCache<unknown, Result>β
The underlying cache instance.
Type Parametersβ
Args: Args extends unknown[]β
The argument types of the function.
Result: Resultβ
The return type of the function.
Sinceβ
2.0.0