Skip to content

Instantly share code, notes, and snippets.

@beastaugh
Created September 30, 2009 13:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save beastaugh/198106 to your computer and use it in GitHub Desktop.
Save beastaugh/198106 to your computer and use it in GitHub Desktop.
Calculate Fibonacci numbers in JavaScript
/**
* 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];
};
})();
@jerrygreen
Copy link

Neat implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment