memoize
function
Creates a function that memoizes the result of func.
Installation
Import
import { memoize } from '@tulx/utils';Source Code
Implementation
/**
* Creates a function that memoizes the result of func.
*
* @param func - The function to have its output memoized.
* @param resolver - The function to resolve the cache key.
* @returns Returns the new memoized function.
*
* @example
* ```ts
* const object = { 'a': 1, 'b': 2 };
* const other = { 'c': 3, 'd': 4 };
* const values = memoize((obj: Record<string, number>) => Object.values(obj));
* values(object); // [1, 2]
* values(other); // [3, 4]
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function memoize<T extends (...args: any[]) => any>(
func: T,
resolver?: (...args: Parameters<T>) => string
): T & { cache: Map<string, ReturnType<T>> } {
const cache = new Map<string, ReturnType<T>>();
const getKey =
resolver ??
((...args: Parameters<T>) => {
// Optimize for single primitive argument
if (args.length === 1) {
const arg = args[0];
if (
typeof arg === 'string' ||
typeof arg === 'number' ||
typeof arg === 'boolean' ||
arg === null ||
arg === undefined
) {
return String(arg);
}
}
return JSON.stringify(args);
});
const memoized = function (
this: unknown,
...args: Parameters<T>
): ReturnType<T> {
const key = getKey(...args);
if (cache.has(key)) {
return cache.get(key)!;
}
const result = func.apply(this, args) as ReturnType<T>;
cache.set(key, result);
return result;
} as T & { cache: Map<string, ReturnType<T>> };
memoized.cache = cache;
return memoized;
}
Example
import { memoize } from '@tulx/utils';
const object = { 'a': 1, 'b': 2 };
const other = { 'c': 3, 'd': 4 };
const values = memoize((obj: Record<string, number>) => Object.values(obj));
values(object); // [1, 2]
values(other); // [3, 4]Related Functions
after
The opposite of before; this method creates a function that invokes func once it's called n or more times.
ary
Creates a function that invokes func, with up to n arguments, ignoring any additional arguments.
before
Creates a function that invokes func, with the this binding and arguments of the created function, while it's called less than n times.
bind
Creates a function that invokes func with the this binding of thisArg and partials prepended to the arguments it receives.
bindKey
Creates a function that invokes the method at object[key] with partials prepended to the arguments it receives.
curry
Creates a function that accepts arguments of func and either invokes func returning its result, or returns a function that accepts the remaining arguments.