Skip to content

Instantly share code, notes, and snippets.

@monkeymonk
Created July 13, 2019 18:38
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 monkeymonk/a1d2862858e192cf9fb21041d751123e to your computer and use it in GitHub Desktop.
Save monkeymonk/a1d2862858e192cf9fb21041d751123e to your computer and use it in GitHub Desktop.
Memoization helper
/**
* Memoization helper.
* @param fn
* @param context
* @return Function
*/
export default function memoize(fn, context = null) {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
if (typeof cache[key] === 'undefined') {
if (fn === null || typeof fn === 'number' || typeof fn === 'undefined' || typeof fn.call === 'undefined') {
cache[key] = fn;
} else {
cache[key] = fn.call(context, ...args);
}
}
return cache[key];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment