Skip to content

Instantly share code, notes, and snippets.

@erikvullings
Created May 31, 2018 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikvullings/76a42084d1d906ae4d47a76e55c23135 to your computer and use it in GitHub Desktop.
Save erikvullings/76a42084d1d906ae4d47a76e55c23135 to your computer and use it in GitHub Desktop.
Created a cached version of any function with a single argument.
/**
* 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