Created
August 15, 2018 08:36
-
-
Save seralexeev/f3a4249ebb3a6c8277447e016563f4ea to your computer and use it in GitHub Desktop.
Implementing Memoization in Typescript
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
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