Skip to content

Instantly share code, notes, and snippets.

@burakozturk16
Created October 20, 2021 09:33
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 burakozturk16/70399c3da1e3ed2e88a4446b4b8bf591 to your computer and use it in GitHub Desktop.
Save burakozturk16/70399c3da1e3ed2e88a4446b4b8bf591 to your computer and use it in GitHub Desktop.
Javascript function cache
const memoize = (fn) => {
let cache = {};
return (...args) => {
let n = fn(...args);
if (n in cache) {
console.log('Result from cache', cache[n]);
return cache[n];
}
else {
console.log('Result from execute', fn(...args));
let result = fn(...args);
cache[n] = result;
return result;
}
}
}
// for testing..
const add = (a,b) => (a+b);
const mul = (a,b) => (a*b);
const memoizedAdd = memoize(add);
const memoizedMul = memoize(mul);
memoizedAdd(1,2);
memoizedAdd(1,2);
memoizedMul(3,5);
memoizedMul(3,5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment