Skip to content

Instantly share code, notes, and snippets.

@ktutnik
Last active April 3, 2019 02:29
Show Gist options
  • Save ktutnik/688f364e245f00d04d76d0cb51d433c8 to your computer and use it in GitHub Desktop.
Save ktutnik/688f364e245f00d04d76d0cb51d433c8 to your computer and use it in GitHub Desktop.
Higher order cache
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