Last active
August 29, 2015 14:19
-
-
Save alastairparagas/faac559891686f740665 to your computer and use it in GitHub Desktop.
Fibonacci Sequence Adder Game in Javascript. Got bored while doing homework so I wrote this in ~10 minutes. F12 on your browser, copy the code, paste it in that window that shows up (called a Developer Console) and play along!
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
// Function scoped - prevent global namespace pollution | |
(function (window) { | |
'use strict'; | |
// Bootstraps our Fibonacci program | |
function runProgram() { | |
/* | |
Recursive function with two base cases: | |
First 2 terms of Fibonacci sequence are 0 and 1. | |
The next terms after those terms are the sum of the | |
two previous terms. | |
*/ | |
function fibonacci(termsToAdd) { | |
if (termsToAdd === 1) { | |
return 0; | |
} else if (termsToAdd === 2) { | |
return 1; | |
} | |
return fibonacci(termsToAdd - 1) + fibonacci(termsToAdd - 2); | |
} | |
// By default, input is 0 unless the user puts something in | |
var input | |
= Number(window.prompt("How many Fibonacci Terms to add up?")) || 0, | |
playAgain; | |
// Protect against invalid input | |
if (window.isNaN(input)) { | |
window.alert("Inappropriate input - input must be a number!"); | |
} else { | |
window.alert("The sum of Fibonacci sequence of the first " | |
+ input + " term/s is " + fibonacci(input)); | |
} | |
playAgain | |
= window.prompt("Play Again? Yes or No?").toLowerCase() || "yes"; | |
// If you notice, this is a double recursion program... sneaky sneaky | |
if (playAgain === "yes") { | |
runProgram(); | |
} | |
} | |
// Run our Fibonacci program! | |
runProgram(); | |
}(window)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
c00l. but it doesn't output the sum of the first input n terms. it outputs the number at position n in the sequence.