-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
76 lines (68 loc) · 2.17 KB
/
script.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
let displayValue = '0';
let firstOperand = null;
let waitingForSecondOperand = false;
let operator = null;
function updateDisplay() {
const display = document.getElementById('display');
display.innerText = displayValue;
}
function clearDisplay() {
displayValue = '0';
firstOperand = null;
waitingForSecondOperand = false;
operator = null;
updateDisplay();
}
function inputDigit(digit) {
if (waitingForSecondOperand === true) {
displayValue = digit;
waitingForSecondOperand = false;
} else {
displayValue = displayValue === '0' ? digit : displayValue + digit;
}
updateDisplay();
}
function inputDecimal() {
if (waitingForSecondOperand === true) {
displayValue = '0.';
waitingForSecondOperand = false;
} else if (!displayValue.toString().includes('.')) {
displayValue += '.';
}
updateDisplay();
}
function inputOperator(nextOperator) {
const inputValue = parseFloat(displayValue);
if (operator && waitingForSecondOperand) {
operator = nextOperator;
return;
}
if (firstOperand === null) {
firstOperand = inputValue;
} else if (operator) {
const result = performCalculation[operator](firstOperand, inputValue);
displayValue = `${parseFloat(result.toFixed(7))}`;
firstOperand = result;
}
waitingForSecondOperand = true;
operator = nextOperator;
updateDisplay();
}
const performCalculation = {
'/': (firstOperand, secondOperand) => firstOperand / secondOperand,
'*': (firstOperand, secondOperand) => firstOperand * secondOperand,
'+': (firstOperand, secondOperand) => firstOperand + secondOperand,
'-': (firstOperand, secondOperand) => firstOperand - secondOperand,
'%': (firstOperand, secondOperand) => firstOperand % secondOperand,
};
function calculate() {
if (operator && !waitingForSecondOperand) {
const result = performCalculation[operator](firstOperand, parseFloat(displayValue));
displayValue = `${parseFloat(result.toFixed(7))}`;
firstOperand = null;
operator = null;
waitingForSecondOperand = false;
updateDisplay();
}
}
updateDisplay();