The Code for FIZZ BUZZ
getValues()
getValues is a controller function that gets the user's fizz and buzz values from the page so that they can be displayed as multiples for the numbers 1 to 100. It parses the fizz and buzz values as integers and then passes them along with an array of numbers 1 to 100 to a display function where they are all printed to the screen.
//get the values from the Page
//starts or controller function
function getValues() {
//get values from the page
let fizzValue = document.getElementById("fizzValue").value;
let buzzValue = document.getElementById("buzzValue").value;
//Need to validate input
//parse into integers
fizzValue = parseInt(fizzValue);
buzzValue = parseInt(buzzValue);
if (Number.isInteger(fizzValue) && Number.isInteger(buzzValue)) {
//call generateNumbers
let numbers = generateNumbers();
//call displayNumbers
displayNumbers(fizzValue, buzzValue, numbers);
} else {
alert("You must enter integers");
}
}
generateNumbers()
generateNumbers is a logic function that generates and transfers numbers 1 to 100 into an array using a for loop, and then returns the number array to the calling function.
//logic function
function generateNumbers() {
let numbers = [];
//get all numbers from start to end
for (let index = 1; index <= 100; index++) {
//execute in a loop until index = eValue
numbers.push(index);
}
return numbers;
}
displayNumbers(fValue, bValue, numbers)
displayNumbers is a display function that displays fizz and buzz values for the numbers 1 to 100 on to the page. Both the fizz and buzz values are passed into the function along with the number array. These values are processed using a for loop and if-then-else conditional statements. They are templated on to the page using different colors to maximize user readability.
//display or view functions
function displayNumbers(fValue, bValue, numbers) {
let templateRows = "";
for (let index = 0; index < numbers.length; index++) {
let className = "";
let number = numbers[index];
if (index % 5 == 0) {
templateRows += ``;
}
if (number % fValue == 0 && number % bValue == 0) {
className = "fizzBuzz";
templateRows += `${className}`;
}
else if (number % fValue == 0) {
className = "fizz";
templateRows += `${className}`;
}
else if (number % bValue == 0){
className = "buzz";
templateRows += `${className}`;
}
else {
templateRows += `${number}`;
}
if ((index + 1) % 5 == 0) {
templateRows += ``;
}
}
document.getElementById("results").innerHTML = templateRows;
}