Skip to content

Instantly share code, notes, and snippets.

@parkerproject
Created April 10, 2023 02:36
Show Gist options
  • Save parkerproject/6935930bf4d897ec46753f021ee7a37f to your computer and use it in GitHub Desktop.
Save parkerproject/6935930bf4d897ec46753f021ee7a37f to your computer and use it in GitHub Desktop.
/*
This memoize function takes in another function as its argument (func)
and returns a new function that caches the results of func based on its arguments.
The returned function first checks if the arguments have already been cached
by checking if there is a key in the cache object with the same JSON stringified arguments (key).
If there is a cached value, it returns it. If not, it invokes the original function func with the arguments,
caches the result under the key, and returns the result.
*/
function memoize(func) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
} else {
const result = func.apply(this, args);
cache[key] = result;
return result;
}
}
}
// You can use this memoize function like this:
function expensiveCalculation(n) {
console.log(`Calculating for ${n}...`);
return n * n;
}
const memoizedCalculation = memoize(expensiveCalculation);
console.log(memoizedCalculation(2)); // "Calculating for 2..." then 4
console.log(memoizedCalculation(2)); // 4 (retrieved from cache)
console.log(memoizedCalculation(3)); // "Calculating for 3..." then 9
console.log(memoizedCalculation(3)); // 9 (retrieved from cache)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment