Created
January 30, 2020 11:45
-
-
Save sanishkr/e9ad3198d998709f3a3759f675f54994 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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