The Code
///INITIATION:
//Program Entry points
function getValues2() {
let startValue = document.getElementById("startValue").value;
let endValue = document.getElementById("endValue").value;
//VALIDATION:
startValue = parseInt(startValue);
endValue = parseInt(endValue);
//check to see if input is integer
if (Number.isInteger(startValue) && Number.isInteger(endValue)) {
//generate list of numbers
let numbers = generateNumbers(startValue, endValue);
displayNumbers(numbers);
} else {
Swal.fire({
icon: "error",
title: "oops",
text: "only integers are allowed for JS Speedway"
})
}
}
//LOGIC:
function generateNumbers(start, end) {
let numbers = [];
for (let index = start; index <= end; index++) {
numbers.push(index);
}
return numbers;
}
//DISPLAY:
function displayNumbers(numbers) {
let templateRows="" ;
let className="even" ;
for (let index=0; index < numbers.length; index++) {
let number=numbers[index];
if (number % 2===0) {
className="even" ;
} else {
className="odd" ;
}
let row=`${number} `;
templateRows += row;
}
document.getElementById("results").innerHTML = templateRows;
}
The code is structured in three functions.
.JS Speedway
.JS Speedway is a simple program looping input integers and displaying them to the page. Even numbers are bolded.
Brief code overview:
- Initiation:
- event listener (located in the bottom <script> tag) is triggered by a "click" on the "submit" button.
- Inputs from the two user fields ("Start Value" and "End Value") are passed into the "Get Values" function.
- Validation:
- Inputs are checked to make certain they are integers (numbers) and not strings.
- If inputs are numbers treated as strings, the program parses them to integers.
- If inputs are text, the system will alert the user, "Only integers are allowed for JS Speedway."
- Logic:
Within the "Generate Numbers" function, the following processes occur:
- the "numbers" array is created
- the "for" loop passes the start value and increments the number by one.
- the produced number is pushed to the "numbers" array.
- Meanwhile, produced numbers are re-introduced into the loop until the incremented number is equal to the End Value.
- the function returns the "numbers" array.
- Display:
- Inside the "for" loop:
- A boolean tests each number in the "numbers" array by dividing each number by 2 to determine whether the number is even.
- Numbers testing "true" are bolded.
- Numbers testing "false" are not bolded.
- "Template Rows" variable injects the "Number" variable (from the "Display Numbers" function) into the template literal.
- Finally, "Template Rows" are published to the HTML via the "results" class.