odin-calculator/script.js

130 lines
3.3 KiB
JavaScript
Raw Normal View History

const viewDiv = document.querySelector("#view");
const signGui = viewDiv.querySelector("#sign");
const valueGui = viewDiv.querySelector("#value");
2024-01-11 22:20:16 +00:00
function add(a, b) {
return a + b;
}
function substract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
return a / b;
}
function operate(equals) {
switch(equals.operator) {
case "+":
return add(+equals.a, +equals.b);
2024-01-11 22:20:16 +00:00
case "-":
return substract(+equals.a, +equals.b);
2024-01-11 22:20:16 +00:00
case "*":
return multiply(+equals.a, +equals.b);
2024-01-11 22:20:16 +00:00
case "/":
return divide(+equals.a, +equals.b);
2024-01-11 22:20:16 +00:00
}
}
function execute(operation) {
if (operation.equal) {
const result = operate(operation);
operation.a_b = !operation.a_b;
operation.equal = false;
operation.operator = "";
if (operation.a_b) {
operation.a = `${result}`;
operation.b = "";
operation.equasion_val = true;
valueGui.textContent = `${operation.a}`;
}
console.table(operation);
console.log(`Result: ${result}`);
}
}
2024-01-11 22:20:16 +00:00
let operation = {
a: "",
operator: "",
b: "",
a_b: true,
equal: false,
equasion_val: false,
}
let equal = "";
function click(value) {
if (!isNaN(+value)) {
if (operation.equasion_val) {
operation.a = value;
operation.equasion_val = !operation.equasion_val;
signGui.textContent = "";
valueGui.textContent = `${operation.a}`;
operation.a_b = true;
} else {
if (operation.a_b) {
if (operation.a == "0") {
operation.a = "";
}
operation.a += value;
valueGui.textContent = `${operation.a}`;
} else {
if (operation.b == "0") {
operation.b = "";
}
operation.b += value;
operation.equal = true;
valueGui.textContent = `${operation.b}`;
}
}
} else if (value == "=") {
execute(operation);
signGui.textContent = value;
} else {
if (operation.operator == "") {
operation.a_b = !operation.a_b;
operation.operator = value;
signGui.textContent = value;
}
if (operation.a_b) {
operation.operator = value;
}
}
console.table(operation);
}
function generateGui() {
const buttonsValues = [
[7,8,9,"+"],
[4,5,6,"-"],
[1,2,3,"*"],
[0,".","=","/"],
];
const buttonsDiv = document.querySelector("#buttons");
for (let i = 0; i < 4; i++) {
let button_row = document.createElement("div");
button_row.classList.add("buttons-flex");
for (let j = 0; j < 4; j++) {
let button = document.createElement("div");
button.classList.add("button");
button.setAttribute("value", buttonsValues[i][j]);
button.textContent = `${buttonsValues[i][j]}`;
button.addEventListener("click", (event) => {
click(event.target.getAttribute("value"));
});
button_row.append(button);
}
buttonsDiv.append(button_row);
}
}
generateGui();