forked from MTalhaofc/HacktoberFest-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.js
59 lines (54 loc) · 1.47 KB
/
calc.js
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
let displayValue = '';
let currentOperator = '';
let firstOperand = null;
function appendNumber(number) {
displayValue += number;
updateDisplay();
}
function setOperator(operator) {
if (displayValue !== '') {
if (firstOperand === null) {
firstOperand = parseFloat(displayValue);
} else if (currentOperator) {
calculate();
}
currentOperator = operator;
displayValue = '';
}
}
function calculate() {
if (currentOperator && displayValue !== '') {
const secondOperand = parseFloat(displayValue);
switch (currentOperator) {
case '+':
firstOperand += secondOperand;
break;
case '-':
firstOperand -= secondOperand;
break;
case '*':
firstOperand *= secondOperand;
break;
case '/':
if (secondOperand === 0) {
alert("Cannot divide by zero");
clearDisplay();
return;
}
firstOperand /= secondOperand;
break;
}
displayValue = firstOperand.toString();
currentOperator = '';
updateDisplay();
}
}
function clearDisplay() {
displayValue = '';
currentOperator = '';
firstOperand = null;
updateDisplay();
}
function updateDisplay() {
document.getElementById('display').value = displayValue;
}