Fibonacci Generator in JavaScript

Fibonacci is always a fun and easy algorithm to implement.

(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));
view raw fibonacci.js hosted with ❤ by GitHub