1.38.0memoize
Caches the result of a function and reuses it when the same cache key is requested again.
memoize(fn, resolver):(...args: TArgs) => TResultParameters
fn(...args: TArgs) => TResultrequiredThe function whose results should be cached.
resolver(...args: TArgs) => unknownoptionalOptional function used to generate the cache key from the arguments.
Returns
(...args: TArgs) => TResultReturns a function that caches and reuses the results of the original function.
Examples
Basic usage
The result for the same argument is calculated only once.
const calculate = memoize((value: number) => {
console.log("Calculating...");
return value * 2;
});
console.log(calculate(5));
// Calculating...
// 10
console.log(calculate(5));
// 10Multiple arguments
When no resolver is provided, multiple arguments are serialized with JSON.stringify to create the cache key.
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));
// 5Using a resolver
A resolver can define a custom cache key from the function arguments.
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" }Single argument
With a single argument and no resolver, that argument itself is used as the cache key.
const square = memoize((value: number) => value * value);
console.log(square(4));
// 16
console.log(square(4));
// 16Different arguments
Different cache keys cause the original function to execute separately.
const double = memoize((value: number) => {
console.log("Calculating...");
return value * 2;
});
console.log(double(5));
// Calculating...
// 10
console.log(double(10));
// Calculating...
// 20Caching object results
The returned result is stored and the same cached result is returned for subsequent calls with the same key.
const createUser = memoize((name: string) => ({
name,
}));
const first = createUser("Amir");
const second = createUser("Amir");
console.log(first === second);
// true