Skip to content

Instantly share code, notes, and snippets.

@ktutnik
Created March 27, 2019 06:30
Show Gist options
  • Save ktutnik/7dd16b0e28ef99d7f04603675b9b550c to your computer and use it in GitHub Desktop.
Save ktutnik/7dd16b0e28ef99d7f04603675b9b550c to your computer and use it in GitHub Desktop.
TypeScript HOF cache
type Fun<A extends any[], B> = (...args:A) => B
type Cache<T> = {[key:string]: T}
function cache<P extends any[], R>(cache: Cache<R>, fn: Fun<P, R>, getKey: Fun<P, string>) {
return (...args: P) => {
const key = getKey(...args)
const saved = cache[key]
if (!!saved) return saved
else return cache[key] = fn(...args)
}
}
/*
How to use it
for example we have slow fuction that will be cached on each call
*/
function slowFuntion(id:string, offset:number){
//implementation
//return number
}
/*
create cached function using function above
*/
const memoryCache:Cache<number> = {}
const slowFunctionCached = cache(memoryCache, slowFunction, (id, offset) => id)
const result = slowFunctionCached(<id>, <offset>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment