Created
May 31, 2018 08:00
-
-
Save erikvullings/76a42084d1d906ae4d47a76e55c23135 to your computer and use it in GitHub Desktop.
Created a cached version of any function with a single argument.
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
/** | |
* Create a cached version of a function. | |
* | |
* @example cachedCalcArea = cachify(calcArea); | |
* @param fn Function whose results you want to cache | |
* @see TypeScript version of https://dev.to/kepta/javascript-underdogs-part-1---the-weakmap-4jih | |
*/ | |
export const cachify = <T extends object, R>(fn: (arg: T) => R) => { | |
const cache = new WeakMap(); // Use Map() when dealing with non-object arguments | |
return (arg: T) => { | |
if (cache.has(arg)) { | |
return cache.get(arg); | |
} | |
const computed = fn(arg); | |
cache.set(arg, computed); | |
return computed; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment