Last active
December 20, 2015 18:48
-
-
Save PatrickJS/6178562 to your computer and use it in GitHub Desktop.
Another method is to memoize the recursive function by extending it with a cache defined inside a closure. This combines the simplicity of the recursive method with the advantages of only calculating each value once.
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
| var fibClosure = (function() { | |
| var cache = [0,1,1]; | |
| return function(n) { | |
| if (cache[n] === undefined) { | |
| cache[n] = fibClosure(n - 1) + fibClosure(n - 2); | |
| } | |
| return cache[n]; | |
| }; | |
| }()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment