Skip to content

Instantly share code, notes, and snippets.

@alastairparagas
Last active August 29, 2015 14:19
Show Gist options
  • Save alastairparagas/faac559891686f740665 to your computer and use it in GitHub Desktop.
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!
// 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));
Copy link

ghost commented May 4, 2015

c00l. but it doesn't output the sum of the first input n terms. it outputs the number at position n in the sequence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment