Skip to content

Instantly share code, notes, and snippets.

@jahilldev
Created July 8, 2022 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jahilldev/c4fce3ed9c7c6f645b4c798a3c30cd5f to your computer and use it in GitHub Desktop.
Save jahilldev/c4fce3ed9c7c6f645b4c798a3c30cd5f to your computer and use it in GitHub Desktop.
Fully typed Memoize function, maintains argument function and expected return types
function memoize<T extends (...args: any[]) => any>(
func: T
): (...funcArgs: Parameters<T>) => ReturnType<T> {
const results = {};
return (...args: Parameters<T>): ReturnType<T> => {
const cacheKey = JSON.stringify(args);
if (!results[cacheKey]) {
results[cacheKey] = func(...args);
}
return results[cacheKey];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment