-
-
Save SabrinaMarkon/4f602c0a2235d47ba087adb3ac64d11f to your computer and use it in GitHub Desktop.
This file contains hidden or 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