Skip to content

Instantly share code, notes, and snippets.

@iamshadmirza
Created December 4, 2019 01:41
Show Gist options
  • Save iamshadmirza/73a8233720c5d1e28c114a8cadb924dd to your computer and use it in GitHub Desktop.
Save iamshadmirza/73a8233720c5d1e28c114a8cadb924dd to your computer and use it in GitHub Desktop.
Cache recursive calls to optimize runtime
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