Skip to content

Instantly share code, notes, and snippets.

@jerrygreen
Forked from beastaugh/fib.js
Created July 2, 2021 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerrygreen/f2509f9d9b50afb63883111a084c8103 to your computer and use it in GitHub Desktop.
Save jerrygreen/f2509f9d9b50afb63883111a084c8103 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];
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment