Skip to content

Instantly share code, notes, and snippets.

@draeton
Created August 3, 2011 12:26
Show Gist options
  • Save draeton/1122517 to your computer and use it in GitHub Desktop.
Save draeton/1122517 to your computer and use it in GitHub Desktop.
Fibonacci generator
(function (window, undefined) {
var Math = window.Math,
a = [0, 1];
if (!Math.fibonacci) {
Math.fibonacci = function (n) {
var i;
if (a[n] === undefined) {
if (typeof n !== 'number' || n < 0 || Math.floor(n) < n) {
throw new RangeError("'" + n + "' is not a valid Fibonacci index.");
}
for (i = a.length - 1; i < n; i++) {
a.push(a[i] + a[i - 1]);
}
}
return a[n];
};
}
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment