odin-calculator/script.js

105 lines
2.4 KiB
JavaScript
Raw Normal View History

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 = "";
}
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,
}
let equal = "";
function click(value) {
if (!isNaN(+value)) {
if (operation.a_b) {
operation.a += value;
} else {
operation.b += value;
operation.equal = true;
}
} else if (value == "=") {
execute(operation);
} else {
if (operation.operator == "") {
operation.a_b = !operation.a_b;
operation.operator = 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();