Created
March 27, 2019 06:30
-
-
Save ktutnik/7dd16b0e28ef99d7f04603675b9b550c to your computer and use it in GitHub Desktop.
TypeScript HOF 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
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