Skip to content

Instantly share code, notes, and snippets.

@codeepic
Created July 31, 2019 09:45
Show Gist options
  • Save codeepic/cac9aeb1e49a35af0e28094b420ccec3 to your computer and use it in GitHub Desktop.
Save codeepic/cac9aeb1e49a35af0e28094b420ccec3 to your computer and use it in GitHub Desktop.
Memoize - function that memoizes other functions.
/**
* @param fn - a pure (no side effects) function you want to memoize
* if you run a memoized function again with the same arguments,
* it will return the cached result instead of running the computation
*/
const memoize = fn => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
if (key in cache) {
return cache[key];
} else {
const result = fn(...args);
cache[key] = result;
return result;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment