-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
107 lines (89 loc) · 2.78 KB
/
app.js
File metadata and controls
107 lines (89 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const display = document.querySelector('.display');
const btnZero = document.querySelector("#btnZero");
const btnOne = document.querySelector("#btnOne");
const btnTwo = document.querySelector("#btnTwo");
const btnThree = document.querySelector("#btnThree");
const btnFour = document.querySelector("#btnFour");
const btnFive = document.querySelector("#btnFive");
const btnSix = document.querySelector("#btnSix");
const btnSeven = document.querySelector("#btnSeven");
const btnEight = document.querySelector("#btnEight");
const btnNine = document.querySelector("#btnNine");
const isOperator = (char) => {
return ['+', '-', '*', '/', '%', '.'].includes(char);
}
const operator = (operator) => {
const lastChar = display.innerText.slice(-1);
if (!isOperator(lastChar)) {
display.innerText += operator;
}
}
const add = () => {
operator("+");
}
const subtract = () => {
operator("-");
}
const multiply = () => {
operator("*");
}
const divide = () => {
operator("/");
}
const percent = () => {
operator("%");
}
const point = () => {
const displayValue = display.innerText;
// Get the last part of the expression (after the last operator)
const parts = displayValue.split(/[\+\-\*\/]/);
const lastPart = parts[parts.length - 1];
// If the last part already contains a decimal point, don't add another
if (!lastPart.includes('.')) {
// If display shows only 0, add "0."
if (displayValue === "0") {
display.innerText += ".";
} else {
// Add decimal point only if last character isn't already an operator
const lastChar = displayValue.slice(-1);
if (!isOperator(lastChar)) {
display.innerText += '.';
} else {
// If last character is an operator, add "0."
display.innerText += "0.";
}
}
}
}
const percentOp = () => {
const currentValue = display.innerText;
if (currentValue !== "0") {
const parts = currentValue.split(/[\+\-\*\/]/);
const lastNumber = parts[parts.length - 1];
if (lastNumber) {
const percentValue = parseFloat(lastNumber) / 100;
display.innerText = currentValue.substring(0, currentValue.length - lastNumber.length) + percentValue;
}
}
}
const calc = (num) => {
if (display.innerText == "0") {
display.innerText = num;
} else {
display.innerText += num;
}
}
const reset = () => {
display.innerText = "0";
}
const res = () => {
let expression = display.innerText.replace(/%/g, "/100");
try {
display.innerText = eval(expression);
} catch (error) {
display.innerText = "Error";
setTimeout(() => {
display.innerText = "0";
}, 1000);
}
}