Skip to content

Instantly share code, notes, and snippets.

@sanishkr
Created January 30, 2020 11:45
Show Gist options
  • Save sanishkr/e9ad3198d998709f3a3759f675f54994 to your computer and use it in GitHub Desktop.
Save sanishkr/e9ad3198d998709f3a3759f675f54994 to your computer and use it in GitHub Desktop.
// Main Memoize function
const memo = fn => {
const cache = {}
return function () {
const key = JSON.stringify(arguments);
if(key in cache){
return cache[key]
} else {
cache[key] = fn.apply(this, arguments);
return cache[key]
}
}
}
// Example #1
const factorial = memo( n => {
console.log("calculating for:",n)
return n > 1 ? factorial(n-1) * n : 1
})
console.log(factorial(4))
console.log(factorial(5))
// Example #2
// var fib = memo(function(n){
// if (n < 2){
// return 1;
// }else{
// console.log("loading...");
// return fib(n-2) + fib(n-1);
// }
// });
// console.log(fib(3))
// console.log(fib(4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment