Per the Odin Project’s instructions, I need to make my basic calculator operate via math functions rather than using eval(). https://www.theodinproject.com/lessons/foundations-calculator
I’ve only added the addition part to my mathWorks function. However, I’m not sure how to tie my mathWorks function to my else if block when "=" is selected. Any help would be greatly appreciated.
const container = document.querySelector(".container");
const calcBody = document.querySelector("#calcBody");
const input = document.querySelector("#input");
let a = "";
let b = "";
let operator = "";
let result = "";
const numbers = {
reset: "CE",
goBack: "C",
divide: "/",
multiply: "*",
seven: 7,
eight: 8,
nine: 9,
add: "+",
four: 4,
five: 5,
six: 6,
minus: "-",
one: 1,
two: 2,
three: 3,
decimal: ".",
zero: 0,
equal: "=",
};
for (let key in numbers) {
let button = document.createElement("button");
button.setAttribute("id", key);
button.textContent = numbers[key];
container.appendChild(button);
button.addEventListener("click", (e) => {
let val = e.target.textContent;
if(e.target.textContent === "+" ||
e.target.textContent === "/" ||
e.target.textContent === "*")
{
operator = val;
input.textContent = a + " " + operator + " ";
}
else if(e.target.textContent === "CE") {
input.textContent = "";
a = "";
}
else if(input.textContent.includes("*") ||
input.textContent.includes("+") ||
input.textContent.includes("/")) {
b += val;
input.textContent = a + " " + operator + " " + b;
}
else if(e.target.textContent === "="){
mathWorks();
}
else
{
a += val
input.textContent = a;
}
});
function mathWorks(){
if(operator === "+"){
result = parseFloat(a) + parseFloat(b);
input.textContent = result;
}
}
}
I’m kind of at a loss at the moment. I’ve tried adding parseFloat and including a and b in mathWorks parameters.
2
Answers
The issue seems to be that the mathWorks function is not being called when the "=" button is clicked. This is because the condition else
if(e.target.textContent === "=")
is not being met. The reason for this is that the condition is checked before the b variable is updated with the second operand. Therefore, when the "=" button is clicked, the b variable is still an empty string, and the condition is not met. To fix this, you need to update the b variable before checking if the "=" button was clicked.To fix this, you need to update the b variable before checking if the "=" button was clicked. Here’s how you can do it:
In general, the training tasks for creating a calculator are reduced to more branching and creating functions for all mathematical operators.
If you can use function constructors, then the calculator might look like this: