Skip to content

Instantly share code, notes, and snippets.

@aparx
Last active February 23, 2024 01:35
Show Gist options
  • Save aparx/ac44345bc225ec4ca7c60cb16d2f1d00 to your computer and use it in GitHub Desktop.
Save aparx/ac44345bc225ec4ca7c60cb16d2f1d00 to your computer and use it in GitHub Desktop.
Memoization of a function call, depending on the arguments passed
export function memoize<TMemoizedFn extends (...args: any[]) => any>(
callback: TMemoizedFn,
checkArgs: boolean = true
): TMemoizedFn {
let memoized: true;
let memory: ReturnType<TMemoizedFn>;
let previousArgs: unknown[];
return function __memoized(...args: unknown[]): ReturnType<TMemoizedFn> {
if (!memoized || (checkArgs && !isSameArgs(previousArgs, args))) {
memory = callback(...args);
previousArgs = args;
memoized = true;
}
return memory as ReturnType<TMemoizedFn>;
} as TMemoizedFn;
}
function isSameArgs(
old: unknown[] | undefined,
current: unknown[] | undefined
): boolean {
if (old === current) return true;
if (old == null) return current == null;
if (current == null) return false;
if (old.length !== current.length) return false;
return old.every((e, idx) => Object.is(current[idx], e));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment