odin-calculator/script.js

95 lines
2.6 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 == "back") {
screen.textContent = screen.textContent.trimEnd()
screen.textContent = screen.textContent.slice(0, -1);
if (!isNaN(screen.textContent.charAt(-2))) {
screen.textContent = screen.textContent.trimEnd()
}
} 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
// Add some logic for handling negatives with -
2023-12-27 01:51:17 -07:00
// 0 on a trailing decimal point
// Add key support
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
}
2023-12-27 01:51:17 -07:00
function addDecimals(a, b) {
a = String(a);
b = String(b);
const adec = (a.split(".")[1] || "").length;
const bdec = (b.split(".")[1] || "").length;
const maxdec = Math.max(adec, bdec);
let divdec = "1";
divdec = divdec.padEnd(maxdec, "0");
return ((+a * divdec + +b * divdec) / divdec).toFixed(maxdec);
}
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 = {
2023-12-27 01:51:17 -07:00
"-": (a, b) => addDecimals(a, -b),
"+": (a, b) => addDecimals(a, b),
2023-12-26 17:15:28 -07:00
"/": (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 (a && !b) {
return a;
}
2023-12-26 17:15:28 -07:00
if (isNaN(a) || isNaN(b)) {
return NaN;
}
if (!this.methods[op]) {
return "Operation not supported."
}
return this.methods[op](a, b);
};
}