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

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>

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