Created
October 16, 2021 22:38
-
-
Save brycetshaw/23a28c58a39fb7eaf07e1e38cc3d6435 to your computer and use it in GitHub Desktop.
A memoize function written in typescript.
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< | |
Response, | |
ProvidedFunctionType extends (...args: any[]) => Response | |
>( | |
computeExpensiveValue: ProvidedFunctionType, | |
keyFunction: (...args: any[]) => string, | |
cachingFunction?: () => Map<string, Response> | |
): ProvidedFunctionType { | |
// if no caching object is provided, instanciate a Map instead. | |
const hashMap = cachingFunction ? cachingFunction() : new Map(); | |
const memoizedFunction = (...args: any[]) => { | |
const hashKey = keyFunction(...args); | |
if (hashMap.has(hashKey)) { | |
return hashMap.get(args.toString()); | |
} else { | |
const response = computeExpensiveValue(...args); | |
hashMap.set(hashKey, response); | |
return response; | |
} | |
}; | |
return memoizedFunction as ProvidedFunctionType; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment