Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
101 lines (89 loc) · 2.37 KB
/
Copy pathscript.js
File metadata and controls
101 lines (89 loc) · 2.37 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
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
93
94
95
96
97
98
99
100
101
let display = document.getElementById('display');
let currentInput = '';
let previousInput = '';
let operation = null;
let shouldResetDisplay = false;
function appendNumber(num) {
if (shouldResetDisplay) {
currentInput = num;
shouldResetDisplay = false;
} else {
currentInput += num;
}
updateDisplay();
}
function appendOperator(op) {
if (currentInput === '') return;
if (operation !== null && !shouldResetDisplay) {
calculate();
}
previousInput = currentInput;
operation = op;
shouldResetDisplay = true;
updateDisplay();
}
function calculate() {
if (operation === null || currentInput === '' || previousInput === '') return;
let result;
const prev = parseFloat(previousInput);
const current = parseFloat(currentInput);
switch (operation) {
case '+':
result = prev + current;
break;
case '-':
result = prev - current;
break;
case '*':
result = prev * current;
break;
case '/':
result = current !== 0 ? prev / current : 0;
break;
case '.':
return;
default:
return;
}
currentInput = result.toString();
operation = null;
previousInput = '';
shouldResetDisplay = true;
updateDisplay();
}
function clearDisplay() {
currentInput = '';
previousInput = '';
operation = null;
shouldResetDisplay = false;
updateDisplay();
}
function deleteLast() {
currentInput = currentInput.slice(0, -1);
updateDisplay();
}
function updateDisplay() {
if (operation !== null) {
display.value = previousInput + ' ' + operation + ' ' + currentInput;
} else {
display.value = currentInput || '0';
}
}
// Keyboard support
document.addEventListener('keydown', (e) => {
if (e.key >= '0' && e.key <= '9') appendNumber(e.key);
if (e.key === '.') appendOperator('.');
if (e.key === '+') appendOperator('+');
if (e.key === '-') appendOperator('-');
if (e.key === '*') appendOperator('*');
if (e.key === '/') {
e.preventDefault();
appendOperator('/');
}
if (e.key === 'Enter' || e.key === '=') {
e.preventDefault();
calculate();
}
if (e.key === 'Backspace') deleteLast();
if (e.key === 'Escape') clearDisplay();
});