Skip to content

Instantly share code, notes, and snippets.

@rayinla
Last active December 4, 2019 09:46
Show Gist options
  • Save rayinla/22ec5c5287d8bc2068d2df92129d7124 to your computer and use it in GitHub Desktop.
Save rayinla/22ec5c5287d8bc2068d2df92129d7124 to your computer and use it in GitHub Desktop.
// A more functional memoizer
//We can beef up our module by adding functions later
var Memoizer = (function(){
//Private data
var cache = {};
//named functions are awesome!
function cacher(func){
return function(){
var key = JSON.stringify(arguments);
if(cache[key]){
return cache[key];
}
else{
val = func.apply(this, arguments);
cache[key] = val;
return val;
}
}
}
//Public data
return{
memo: function(func){
return cacher(func);
}
}
})()
var fib = Memoizer.memo(function(n){
if (n < 2){
return 1;
}else{
return fib(n-2) + fib(n-1);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment