The Code Page
function getValues() {
// get values for fizz and buzz
let fizz = document.getElementById("fizzValueID").value;
let buzz = document.getElementById("buzzValueID").value;
// validation
fizz = parseInt(fizz);
buzz = parseInt(buzz)
if (Number.isInteger(fizz) && Number.isInteger(buzz)) {
fizz < -100 || fizz> 100 ? Swal.fire("The number for Fizz is outside of the specified range.") : null;
buzz < -100 || buzz> 100 ? Swal.fire("The number for Buzz is outside of the specified range.") : null;
// clear DOM
writeHTML("");
let numbersArray = new Array(100).fill().map((_, idx) => idx + 1);
genHTML(numbersArray, fizz, buzz);
} else {
Swal.fire("Please Enter Numbers Only");
}
}
// generate the html to be written
function genHTML(numbersArray, fizz, buzz) {
let string = "";
numbersArray.forEach((i) => {
if (i % fizz == 0 && i % buzz == 0) {
// if i % fizz && buzz write fizz buzz
string = `
${i} - FizzBuzz
`;
} else if (i % fizz == 0) {
// if i % fizz write fizz
string = `
${i} - Fizz
`;
} else if (i % buzz == 0) {
// if i % buzz write buzz
string = `
${i} - Buzz
`;
} else {
// if else write number
string = `
${i}
`;
}
writeHTML(string);
})
}
// simple write to element function
function writeHTML(htmlStr) {
let tableBody = document.getElementById("resultsID")
htmlStr == "" ? tableBody.innerHTML = "" : tableBody.innerHTML += htmlStr;
}
The code {...}
getValues()
gets the inputs, validates, clears the DOM, and runs the genHTML function.
genHTML(numbersArray, fizz, buzz)
Takes the numbers 1-100, the user input fizz and buzz, checks if the number is a multiple and creates the html to send back to the DOM.
writeHTML(string)
Takes the html string from genHTML() and writes it to the DOM.