Created
December 4, 2019 01:41
-
-
Save iamshadmirza/73a8233720c5d1e28c114a8cadb924dd to your computer and use it in GitHub Desktop.
Cache recursive calls to optimize runtime
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 stair(n){ | |
if(n === 1){ return 1; } | |
if(n === 2){ return 2; } | |
return memoizedStair(n-1) + memoizedStair(n-2); | |
} | |
function memoize(fn){ | |
const cache = {}; | |
return function(...args){ | |
if(cache[args]){ | |
return cache[args]; | |
} | |
const result = fn.apply(this, args); | |
cache[args] = result; | |
return result; | |
} | |
} | |
const memoizedStair = memoize(stair); | |
console.log(memoizedStair(45)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment