Last active
December 4, 2019 09:46
-
-
Save rayinla/22ec5c5287d8bc2068d2df92129d7124 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
// 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