Skip to content

Instantly share code, notes, and snippets.

@brycetshaw
Created October 16, 2021 22:38
Show Gist options
  • Save brycetshaw/23a28c58a39fb7eaf07e1e38cc3d6435 to your computer and use it in GitHub Desktop.
Save brycetshaw/23a28c58a39fb7eaf07e1e38cc3d6435 to your computer and use it in GitHub Desktop.
A memoize function written in typescript.
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