odin-calculator/script.js

68 lines
1.8 KiB
JavaScript
Raw Normal View History

const screen = document.querySelector(".screen");
const buttons = document.querySelectorAll("button");
const operators = ["+", "-", "*", "/"];
buttons.forEach((button) => {
button.addEventListener ("click", displayToScreen);
});
2023-12-26 22:29:32 -07:00
function displayToScreen() {
2023-12-26 20:12:58 -07:00
if (this.className == "equal") {
2023-12-26 21:25:33 -07:00
let calc = new Calculator;
2023-12-26 22:29:32 -07:00
screen.textContent = calc.calculate(screen.textContent);
2023-12-26 20:12:58 -07:00
} else if (this.className == "clear") {
2023-12-26 22:29:32 -07:00
screen.textContent = "0";
} else {
if (this.className == "operator") {
2023-12-26 22:35:59 -07:00
let screenContent = screen.textContent;
2023-12-26 22:29:32 -07:00
for (let i = 0; i < screenContent.length; i++ ) {
if (operators.includes(screenContent[i])) {
let calc = new Calculator;
2023-12-26 22:29:32 -07:00
result = calc.calculate(screen.textContent);
2023-12-26 22:35:59 -07:00
screen.textContent = result;
break;
}
2023-12-26 22:35:59 -07:00
}
screen.textContent += " " + this.textContent + " ";
2023-12-26 22:29:32 -07:00
} else if (screen.textContent === "0" && this.className == "num") {
screen.textContent = this.textContent;
2023-12-26 21:25:33 -07:00
} else {
2023-12-26 22:29:32 -07:00
screen.textContent += this.textContent;
2023-12-26 21:25:33 -07:00
}
}
2023-12-26 21:25:33 -07:00
}
function Calculator(str) {
console.log("Calculator has been called")
2023-12-26 17:15:28 -07:00
this.methods = {
"-": (a, b) => (a - b),
"+": (a, b) => (a + b),
"/": (a, b) => (a / b),
"*": (a, b) => (a * b)
};
this.calculate = function(str) {
let parts = str.split(" ");
a = +parts[0];
op = parts[1];
b = +parts[2];
if (isNaN(a) || isNaN(b)) {
return NaN;
}
if (!this.methods[op]) {
return "Operation not supported."
}
return this.methods[op](a, b);
};
}