-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
56 lines (50 loc) · 1.3 KB
/
script.js
File metadata and controls
56 lines (50 loc) · 1.3 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
let displayValue = '';
const maxInputLength = 20;
function clearDisplay() {
displayValue = '';
updateDisplay('0');
}
function appendNumber(number) {
if (displayValue.length < maxInputLength) {
displayValue += number;
updateDisplay(displayValue);
}
}
function appendOperator(operator) {
if (displayValue.length < maxInputLength) {
displayValue += operator;
updateDisplay(displayValue);
}
}
function calculate() {
try {
const result = math.evaluate(displayValue);
displayValue = result.toString();
if (displayValue.length > maxInputLength) {
displayValue = parseFloat(displayValue).toExponential(10);
}
updateDisplay(displayValue);
} catch (error) {
updateDisplay('Error');
displayValue = '';
}
}
function updateDisplay(value) {
document.getElementById('display').textContent = value;
}
document.addEventListener('keydown', (event) => {
const key = event.key;
if (!isNaN(key) || key === '.') {
appendNumber(key);
} else if (['+', '-', '*', '/'].includes(key)) {
appendOperator(key);
} else if (key === 'Enter') {
event.preventDefault();
calculate();
} else if (key === 'Backspace') {
displayValue = displayValue.slice(0, -1);
updateDisplay(displayValue || '0');
} else if (key === 'Escape') {
clearDisplay();
}
});