Instantly share code, notes, and snippets.

# mjkaufer/fib.js

Created January 13, 2015 17:52
Show Gist options
• Save mjkaufer/4cb22ee81fb0ace3557d to your computer and use it in GitHub Desktop.
A way to (poorly) generate the first 10 Fibonacci numbers using (almost) only JavaScript array functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 var fib = new Array(10); for(var i = 0; i < fib.length; i++)//strangely enough, setting the values of `a` with array functions is incredibly difficult, so we'll use this instead fib[i] = 1; /*^^Given Code^^*/ /*alternately, you could fill an array using the folloring code var fib = Array.apply(null, new Array(10)).map(Number.prototype.valueOf,10); */ fib.forEach(function(e, i, a){//the arguments passed are e, the element, i, the index, and a, the array - this is honestly just being used as a replacement for a traditional for loop fib = fib.map(function(ee, ii, aa){//this is run through 10 times, as it is nested in the forEach - we update fib //once `i` from the outer loop is equal to `ii`, w if(ii < 2 || ii != i)//if it's in index 0 or 1, it already has its proper value, so we just return its current value //when we check if ii != i, we're checking to see if we're in the correct index, and if we're ready to update stuff return ee; return fib[ii-1] + fib[ii-2];//else, we do the standard fibonacci code }); }) console.log("Finished Fibonacci Below"); console.log(fib);

### 2016rshah commented Jan 14, 2015

Alternatively you could fill the array using:

`var fib = [1,1,1,1,1,1,1,1,1,1]`