The Code for FizzBuzz
// get values from the ui and use them to run the app
function getValues(){
let buzzValue = parseInt(document.getElementById("buzzVal").value);
let fizzValue = parseInt(document.getElementById("fizzVal").value);
let fbValue = fizzValue*buzzValue;
if (isValid(fizzValue) && isValid(buzzValue)) {
displayResults(fizzBuzz(fizzValue,buzzValue,generateNumbers()),fbValue);
}
}
// generate numbers from start value to ending value, set up in case you wanted to alter the
number range
function generateNumbers(){
startVal = 1;
endVal = 100;
let numbers = [];
for (let i = startVal; i < endVal+1; i++) { numbers.push(i); } return numbers;
}
//create the generated numbers, fizz for multiples of fizzValue,
//buzz for multiples of buzzValue, fizzBuzz for multiples of both
function fizzBuzz(fizzValue, buzzValue,numbers){
let tableRow="" ;
let temp="" ;
numbers.forEach(element=> {
if (element % (fizzValue*buzzValue) === 0) {
temp =`FizzBuzz`;
}
else if (element % buzzValue === 0){
temp ="Buzz";
}
else if (element % fizzValue === 0){
temp ="Fizz";
}
else {
temp = element;
}
tableRow += `${temp} `;
});
return tableRow;
}
// displays the generated table and FizzBuzz Value
function displayResults(tableRow,fbValue){
document.getElementById("fbValueHolder").classList.remove("invisible");
document.getElementById("fizzBuzzVal").innerHTML = fbValue;
document.getElementById("results").innerHTML = tableRow;
}
// validate form entry, form only allows integers but full validation listed here
function isValid(number){
if (!Number.isInteger(number)) {
alert("You must enter only Integers.");
}
else if (number < 0){
alert("Value cannot be negative");
}
else if (number===0){
alert("Value cannot be Zero");
}
else {
return true;
}
}
// clear form
function clearForm(){
location.reload();
}
Code was broken out into separate functions to allow for ease of maintenance and to allow for easier changes.
getValues()
Gets the user entered values from the page to pass to the main function. Calls the display function.
generateNumbers()
Generates the number range used, default 1 to 100 per the challenge, but set up to be easily adjustable.
fizzBuzz()
Takes the "Fizz" value and the "Buzz" value used to mark the generated number list. Uses the Modulo (%) operator to check the remainder of a divided term.
displayResults()
Unhide's the computed "FizzBuzz" value of the 2 numbers entered. Displays the values output from the app to the user.
isValid()
Checks the user entered values to ensure they are only positive non-zero integers. Displays an alert box if any invalid entries are attempted.