Created
July 8, 2022 11:32
-
-
Save jahilldev/c4fce3ed9c7c6f645b4c798a3c30cd5f to your computer and use it in GitHub Desktop.
Fully typed Memoize function, maintains argument function and expected return types
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
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