The Code
function getValues() {
let fizz = parseInt(document.getElementById("fizzValue").value);
let buzz = parseInt(document.getElementById("buzzValue").value);
let stop = parseInt(document.getElementById("stopValue").value);
if (
Number.isInteger(fizz) &&
Number.isInteger(buzz) &&
Number.isInteger(stop) &&
stop <= 100 &&
stop > 0
) {
let fizzBuzzes = generateFizzBuzz(fizz, buzz, stop);
displayFizzBuzz(fizzBuzzes);
} else {
Swal.fire({
title: "Oh no!",
text: "Please enter valid integers and make sure the end number is below 100",
icon: "error",
backdrop: false,
});
}
}
// Create an array of values according to the FizzBizz rules e.g. [1, 2, "Fizz", 4, "Buzz"]
function generateFizzBuzz(fizz, buzz, stop) {
let array = [];
for (let number = 1; number <= stop; number++) {
if (number % fizz === 0 && number % buzz === 0) {
array.push("FizzBuzz");
} else if (number % fizz === 0) {
array.push("Fizz");
} else if (number % buzz === 0) {
array.push("Buzz");
} else {
array.push(number);
}
}
return array;
}
// Take in an array of values and display them on the page
function displayFizzBuzz(array) {
let fizzBuzzHTML = "";
for (let i = 0; i < array.length; i++) {
let value = array[i];
let className = "";
if (value === "Fizz") {
className = "fizz-color";
} else if (value === "Buzz") {
className = "buzz-color";
} else if (value === "FizzBuzz") {
className = "fizzbuzz-color";
}
fizzBuzzHTML += ` ${value} `;
}
document.getElementById("results").innerHTML = fizzBuzzHTML;
}
Description
The game takes in three values: fizz, buzz, and stop.
These values are retrieved from the >HTML page using
the document.getElementById method and then parsed into
integers using the parseInt function. The
getValues
function checks if the entered values are valid integers and if the
stop value is less than or equal to 100. If the values
are valid, the function calls the
generateFizzBuzz function, passing in the
fizz, buzz, and stop values as arguments.
The generateFizzBuzz function generates an
array of values according to the
FizzBuzz rules. It iterates from
1 to the stop value and checks if the current number is
divisible by both fizz and buzz, in which case it
pushes “FizzBuzz” to the array. If it is only divisible
by fizz, it pushes “Fizz” to the array. If it is only
divisible by buzz, it pushes “Buzz” to the array.
Otherwise, it pushes the number itself to the array.
The resulting array is then passed to the displayFizzBuzz function,
which takes in an array of values and displays them on the page. The
function iterates over the array and creates an HTML string with a
"div" element for each value. The class name of each
"div" is determined based on whether the value is
“Fizz”, “Buzz”, or “FizzBuzz”. The resulting HTML
string is then added to the page using the
innerHTML property of an element with id
“results”. If the entered values are not valid, an
error message is displayed using the SweetAlert library.