The Code for Even-Handed
//get values from app page
//start OR controller function
function getValues() {
//get values from app page
let startValue = document.getElementById("startValue").value;
let endValue = document.getElementById("endValue").value;
//Validating our inputs
//parsing to Integers
startValue = parseInt(startValue);
endValue = parseInt(endValue);
//if inputs are numbers
if(Number.isInteger(startValue) && Number.isInteger(endValue)) {
//call generateNumbers function
let numbers = generateNumbers(startValue, endValue);
//call displayNumbers function
displayNumbers(numbers);
}
//if inputs are not numbers
else {
alert("You must enter integers for Even-Handed to work!");
}
}
//generate numbers from startValue to endValue
//logic function(s)
function generateNumbers(start, end) {
//create empty array
let numbers = [];
//generating numbers with for loop using start and end values
for(let index = start; index <= end; index++) {
//adding current number to array
numbers.push(index);
}
return numbers;
}
//display numbers and make even numbers bold
//display OR view functions
function displayNumbers(numbers) {
let templateRows = "";
for (let index = 0; index < numbers.length; index++) {
let className = "even";
let number = numbers[index];
if(number % 2 == 0) {
className = "even";
}
else {
className = "odd";
}
//Prism.js has trouble displaying template literals, see source code
templateRows += `${number} `;
}
document.getElementById("results").innerHTML = templateRows;
}
The Code is structured in three functions.
getValues
The getValues function gets user input from the app page. The function utilizes the getElementById to pull values from the page. It then passes those values to the generateNumbers function. The function generateNumbers then returns an array of values and passes that array to the displayNumbers function.
generateNumbers
The generateNumbers function takes in two parameters (startValue and endValue). We create a variable numbers that holds an array. We then use a for loop to generate all the numbers between startValue and endValue.
displayNumbers
The function displayNumbers takes in the parameter numbers (the variable is an array that holds the values between startValue and endValue). We create the variable className that holds the name of the CSS class we will use to bold the numbers. The variable templateRows is then created to hold the HTML we want to write to the app page.
A for loop checks all the numbers to check if they are odd or even. The modulus operator (%) is used to check if a number is divisible by two, making it even, or else it is deemed odd. The correct className is then injected into the html row for display. Each iteration of the loop adds to the templateRows variable. When the loop is done, the resulting HTML rows are then written to our app page for display!