fibonacci series


See On Github

Data

Contributor

Generic placeholder thumbnail

by 3lux

in javascript

Tags

recursion

Source Code


'use strict';

/**
	* A Fibonacci Sequence Generator, implemented in JS.
	* Learn more here: http://en.wikipedia.org/wiki/Fibonacci_number
	* @author Evan Jacobs <evan@evoked.us>

	* Generates a fibonacci sequence of N length.

	* @param {Number} length
	* @param {Number} seed - optional starting number
	* @param {Boolean} debug - set to true to get function timing in your console

	* @returns {Array} an array of fibonacci numbers
	*/

function fibonacci_sequence( length, seed, debug ){

	if(debug) console.time('fibonacci_sequence');

	// By default, we'll start the sequence with 1.
	seed = typeof seed === 'number' ? seed : 1;

	var sequence = [],
		previous = 0;

	while( length-- ){

		// Push seed value
		sequence.push(seed);

		// Prepare for next run
		seed += previous;
		previous = seed - previous;
	}

	if(debug) console.timeEnd('fibonacci_sequence');

	return sequence;
}

// Optimized quick array compare borrowed from here: http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript

function arraysIdentical(a, b) {
	var i = a.length;
	if (i != b.length) return false;
	while (i--) {
		if (a[i] !== b[i]) return false;
	}
	return true;
};

// Equivalent to fibonacci_sequence(20)
var example = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765];

console.assert( arraysIdentical( fibonacci_sequence(20), example ), 'Arrays are not identical.' );