Skip to content

Instantly share code, notes, and snippets.

@seralexeev
Created August 15, 2018 08:36
Show Gist options
  • Save seralexeev/f3a4249ebb3a6c8277447e016563f4ea to your computer and use it in GitHub Desktop.
Save seralexeev/f3a4249ebb3a6c8277447e016563f4ea to your computer and use it in GitHub Desktop.
Implementing Memoization in Typescript
const memoize = <TS extends any[], R>(
fn: (...args: TS) => R,
keyfn: (...args: TS) => string = (...args: TS) => args.map((x, i) => `${i}=${x}`).join("|")
): ((...args: TS) => R) => {
const cache: Record<string, R> = {};
return (...args: TS) => {
const key = keyfn(...args);
return key in cache ? cache[key] : (cache[key] = fn(...args));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment