Skip to content

Instantly share code, notes, and snippets.

@SabrinaMarkon
Forked from rayinla/functional-memo.js
Created March 31, 2019 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SabrinaMarkon/4f602c0a2235d47ba087adb3ac64d11f to your computer and use it in GitHub Desktop.
Save SabrinaMarkon/4f602c0a2235d47ba087adb3ac64d11f 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