Created
September 30, 2009 13:52
-
-
Save beastaugh/198106 to your computer and use it in GitHub Desktop.
Calculate Fibonacci numbers in JavaScript
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
/** | |
* The Fibonacci numbers in JavaScript. | |
* | |
* A cached solution with O(1) lookup for previously-calculated terms and O(N) | |
* lookup for uncalculated ones. | |
* | |
* Because numbers in JavaScript are 64bit, the largest available number is | |
* 1.7976931348623157e+308. The 1476th term is the last that can be calculated. | |
* If a later term is requested, the function will return Infinity. | |
* | |
* See: http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference | |
*/ | |
var fib = (function() { | |
var sequence = [0, 1], | |
updateTo = function(limit) { | |
for (var i = sequence.length; i <= limit; i++) { | |
sequence[i] = sequence[i - 1] + sequence[i - 2]; | |
} | |
}; | |
return function(index) { | |
if (index > 1476) return Infinity; | |
if (!sequence[index]) updateTo(index); | |
return sequence[index]; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Neat implementation