Created
September 13, 2018 16:11
-
-
Save rthangam/b273be62320e6e847a559d4f71ab2786 to your computer and use it in GitHub Desktop.
This file contains 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
function memoize(fn){ | |
return function(){ | |
let args = Array.prototype.slice.call(arguments); | |
let hash = ""; | |
let currentArg = null; | |
let i = args.length; | |
while(i--){ | |
currentArg = args[i]; | |
hash += (currentArg === Object(currentArg))? JSON.stringify(currentArg): | |
currentArg; | |
} | |
fn.memozie || (fn.memoize = {}); | |
return (hash in fn.memoize)? fn.memoize(hash): fn.memoize[hash] = fn.apply(this, args); | |
} | |
} | |
//Fibonacci series | |
function fib(n){ | |
return (n < 2)? 1: fib(n-1) + fib(n - 2); | |
} | |
//Let us test it | |
var fibTest = memoize(fib); | |
console.log("non-memoize result"); | |
console.time("non-memoize"); | |
console.log(fibTest(20)); | |
console.timeEnd("non-memoize"); | |
console.log("memoize result"); | |
console.time("memoize"); | |
console.log(fibTest(20)); | |
console.timeEnd("memoize"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment