-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalc.js
More file actions
52 lines (47 loc) · 1.2 KB
/
calc.js
File metadata and controls
52 lines (47 loc) · 1.2 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
let displayValue = '';
let currentOperation = null;
let firstOperand = null;
function appendNumber(number) {
displayValue += number;
updateDisplay();
}
function chooseOperation(operation) {
if (displayValue === '') return;
if (firstOperand === null) {
firstOperand = parseFloat(displayValue);
} else {
calculate();
}
currentOperation = operation;
displayValue = '';
}
function calculate() {
if (currentOperation === null || displayValue === '') return;
const secondOperand = parseFloat(displayValue);
switch (currentOperation) {
case '+':
firstOperand += secondOperand;
break;
case '-':
firstOperand -= secondOperand;
break;
case '*':
firstOperand *= secondOperand;
break;
case '/':
firstOperand /= secondOperand;
break;
}
displayValue = firstOperand.toString();
currentOperation = null;
updateDisplay();
}
function clearDisplay() {
displayValue = '';
firstOperand = null;
currentOperation = null;
updateDisplay();
}
function updateDisplay() {
document.getElementById('display').value = displayValue;
}