Last active
February 23, 2024 01:35
-
-
Save aparx/ac44345bc225ec4ca7c60cb16d2f1d00 to your computer and use it in GitHub Desktop.
Memoization of a function call, depending on the arguments passed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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