Skip to content

Commit

Permalink
Add code to check the answer and respond to the user
Browse files Browse the repository at this point in the history
  • Loading branch information
RoBizMan committed Mar 6, 2024
1 parent d273891 commit ba1afc5
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion assets/js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ document.addEventListener("DOMContentLoaded", function () {
for (let button of buttons) {
button.addEventListener("click", function () {
if (this.getAttribute("data-type") === "submit") {
alert("You clicked Submit!");
checkAnswer();
} else {
let gameType = this.getAttribute("data-type");
runGame(gameType);
Expand Down Expand Up @@ -36,11 +36,40 @@ function runGame(gameType) {
}
}

/**
* Checks the answer against the first element in
* the returned calculateCorrectAnswer array
*/

function checkAnswer() {
let userAnswer = parseInt(document.getElementById("answer-box").value);
let calculatedAnswer = calculateCorrectAnswer();
let isCorrect = userAnswer === calculatedAnswer[0];

if (isCorrect) {
alert("Hey! You got it right! :D");
} else {
alert(`Awwww.... you answered ${userAnswer}. The correct answer was ${calculatedAnswer[0]}!`);
}

}

/**
* Gets the operands (the numbers) and the operator (plus, minus etc)
* directly from the dom, and returns the correct answer.
*/

function calculateCorrectAnswer() {
let operand1 = parseInt(document.getElementById('operand1').innerText);
let operand2 = parseInt(document.getElementById('operand2').innerText);
let operator = document.getElementById("operator").innerText;

if (operator === "+") {
return [operand1 + operand2, "addition"];
} else {
alert(`Unimplemented operator ${operator}`);
throw `Unimplemented operator ${operator}`;
}

}

Expand Down

0 comments on commit ba1afc5

Please sign in to comment.