CyrefJS
CCyrefJS
فا
Back to documentation
Function/Since 1.38.0

memoize

Caches the result of a function and reuses it when the same cache key is requested again.

memoize(fn, resolver):(...args: TArgs) => TResult

Parameters

fn(...args: TArgs) => TResultrequired

The function whose results should be cached.

resolver(...args: TArgs) => unknownoptional

Optional function used to generate the cache key from the arguments.

Returns

(...args: TArgs) => TResult

Returns a function that caches and reuses the results of the original function.

Examples

01

Basic usage

The result for the same argument is calculated only once.

TypeScript
const calculate = memoize((value: number) => {
  console.log("Calculating...");
  return value * 2;
});

console.log(calculate(5));
// Calculating...
// 10

console.log(calculate(5));
// 10
02

Multiple arguments

When no resolver is provided, multiple arguments are serialized with JSON.stringify to create the cache key.

TypeScript
const add = memoize((a: number, b: number) => {
  console.log("Calculating...");
  return a + b;
});

console.log(add(2, 3));
// Calculating...
// 5

console.log(add(2, 3));
// 5
03

Using a resolver

A resolver can define a custom cache key from the function arguments.

TypeScript
const getUser = memoize(
  (id: number, name: string) => {
    console.log("Fetching user...");
    return { id, name };
  },
  (id) => id,
);

console.log(getUser(1, "Amir"));
// Fetching user...
// { id: 1, name: "Amir" }

console.log(getUser(1, "Ali"));
// { id: 1, name: "Amir" }
04

Single argument

With a single argument and no resolver, that argument itself is used as the cache key.

TypeScript
const square = memoize((value: number) => value * value);

console.log(square(4));
// 16

console.log(square(4));
// 16
05

Different arguments

Different cache keys cause the original function to execute separately.

TypeScript
const double = memoize((value: number) => {
  console.log("Calculating...");
  return value * 2;
});

console.log(double(5));
// Calculating...
// 10

console.log(double(10));
// Calculating...
// 20
06

Caching object results

The returned result is stored and the same cached result is returned for subsequent calls with the same key.

TypeScript
const createUser = memoize((name: string) => ({
  name,
}));

const first = createUser("Amir");
const second = createUser("Amir");

console.log(first === second);
// true
Built with@cyref/js·Official documentation