Skip to content

Instantly share code, notes, and snippets.

@acomagu
Created October 28, 2023 09:22
Show Gist options
  • Save acomagu/c2c0c47d79c78c603e29bef9dad6e1e3 to your computer and use it in GitHub Desktop.
Save acomagu/c2c0c47d79c78c603e29bef9dad6e1e3 to your computer and use it in GitHub Desktop.
TypeScript generic recursive memoization
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