Last active
April 3, 2019 02:29
-
-
Save ktutnik/688f364e245f00d04d76d0cb51d433c8 to your computer and use it in GitHub Desktop.
Higher order cache
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 useCache<K, P extends any[], R>(cache: Map<K, R>, fn: (...args: P) => R, getKey: (...args: P) => K) { | |
return (...args: P) => { | |
const key = getKey(...args) | |
const result = cache.get(key) | |
if(!!result) return result | |
else { | |
const newResult = fn(...args) | |
cache.set(key, newResult) | |
return newResult | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment