Created
October 28, 2023 09:22
-
-
Save acomagu/c2c0c47d79c78c603e29bef9dad6e1e3 to your computer and use it in GitHub Desktop.
TypeScript generic recursive memoization
This file contains hidden or 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
function memoize<Args extends unknown[], R>(f: (...args: Args) => R): (...args: Args) => R { | |
const cache = new Map(); | |
let retCache: { value: R } | undefined; | |
return (...args: Args): R => { | |
if (args.length > 0) { | |
if (!cache.has(args[0])) { | |
cache.set(args[0], memoize((...restArgs) => (f as any)(args[0], ...restArgs))); | |
} | |
return cache.get(args[0])(...args.slice(1)); | |
} | |
if (!retCache) retCache = { value: f(...args) }; | |
return retCache.value; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment