-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (77 loc) · 2.06 KB
/
index.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const calculatorEl = document.querySelector('.calculator');
const displayEl = document.querySelector('.display');
let currentValue = '';
let previousValue = null;
let recentValue = null;
let prevOperator = null;
let clearNext = false;
let isResultCalculated = false;
const appendSymbol = (value, symbol) => {
if (symbol === '.') {
if (value?.includes('.')) {
return value;
}
if (value === '') {
return '0.';
}
return currentValue + symbol;
}
if (currentValue === '' || currentValue === '0') {
return symbol;
}
return currentValue + symbol;
};
const updateDisplay = value => {
displayEl.textContent = value;
};
const performOperation = (operator, a = +previousValue, b = +currentValue) => {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case 'x':
return a * b;
case '/':
return a / b;
}
};
calculatorEl.addEventListener('click', e => {
if (!e.target.classList.contains('btn')) {
return;
}
const symbol = e.target.dataset.value;
if (!Number.isNaN(+symbol) || symbol === '.') {
if (clearNext) {
previousValue = currentValue;
currentValue = '';
clearNext = false;
isResultCalculated = false;
}
currentValue = appendSymbol(currentValue, symbol);
updateDisplay(currentValue);
return;
}
if (symbol === 'c') {
currentValue = '';
recentValue = null;
previousValue = null;
prevOperator = null;
updateDisplay('0');
return;
}
if (!isResultCalculated && (symbol === '=' || prevOperator) && previousValue) {
isResultCalculated = true;
recentValue = currentValue;
currentValue = performOperation(prevOperator);
updateDisplay(currentValue);
} else if (symbol === '=' && prevOperator) {
currentValue = performOperation(prevOperator, +currentValue, +recentValue);
updateDisplay(currentValue);
}
if (symbol !== '=') {
prevOperator = symbol;
}
clearNext = true;
});
updateDisplay('0');