Aller au contenu principal

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​

Overload 2:

fn: (...args) => Result​

The function to memoize.

options?: MemoizeOptions<Args, Result>​


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. Best suited for elements that remain in the DOM throughout the page lifecycle.

const getElement = memoize((selector: string) => document.querySelector(selector));

// Only queries DOM once per selector
const btn = getElement("#submit-btn");
const btnAgain = getElement("#submit-btn"); // Cached

// ⚠️ Cached references become stale if elements are removed/re-added to the DOM

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

Cache responsive breakpoint calculations​

Memoize breakpoint detection to avoid recalculating on every render. Essential for design systems with JS-driven responsive behavior.

const getBreakpoint = memoize((width: number) => {
if (width < 640) return "sm";
if (width < 1024) return "md";
if (width < 1440) return "lg";
return "xl";
});

// Same width returns cached result
const bp = getBreakpoint(window.innerWidth);

Cache media query match results​

Memoize MediaQueryList creation to avoid constructing duplicate objects. Essential for CDK-style BreakpointObserver implementations.

const getMediaQuery = memoize((query: string) => window.matchMedia(query));

// Same query returns cached MediaQueryList — use .matches for current state
const mql = getMediaQuery("(min-width: 1024px)");
console.log(mql.matches); // Always reads live value from the cached MediaQueryList
mql.addEventListener("change", (e) => console.log("Changed:", e.matches));

Cache computed overlay positions​

Cache the result of expensive config or schema parsing that won't change at runtime. Perfect for parsing design tokens, theme definitions, or static configuration.

const parseThemeTokens = memoize((themeJson: string) => {
const raw = JSON.parse(themeJson);
// Expensive: resolve aliases, compute derived values, flatten nested tokens
return resolveTokenAliases(raw);
});

// Same theme string parsed once, cached for subsequent reads
const tokens = parseThemeTokens(rawTheme); // Parsed
const again = parseThemeTokens(rawTheme); // Cache hit

Cache i18n date formatters per locale​

Create and cache Intl.DateTimeFormat instances per locale to avoid repeated construction. Critical for i18n-heavy apps rendering many formatted dates.

const getDateFormatter = memoize((locale: string) => {
return new Intl.DateTimeFormat(locale, {
year: "numeric",
month: "long",
day: "numeric",
});
});

// Formatter created once per locale, reused across renders
getDateFormatter("fr-FR").format(new Date()); // "10 juin 2025"
getDateFormatter("fr-FR").format(anotherDate); // Cache hit on formatter

MemoizeCache<K, V>​

Interface

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>​

Interface

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>​

Type

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