-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.js
72 lines (64 loc) · 1.72 KB
/
calculator.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
document.addEventListener('DOMContentLoaded', function () {
let inputText = '';
let logText = '';
function updateScreen() {
document.querySelector('.input').textContent = inputText;
document.querySelector('.log').textContent = logText;
}
function clearLog() {
logText = '';
updateScreen();
}
function getValue(value) {
if (value === 'C') {
inputText = '';
clearLog();
} else if (value === '<') {
inputText = inputText.slice(0, -1);
} else {
if (inputText.length < 10) {
inputText += value;
}
}
updateScreen();
}
function result() {
// clearLog();
try {
const sanitizedInput = inputText.replace(/[^-()\d/*+.]/g, '');
const resultValue = new Function('return ' + sanitizedInput)();
logText = inputText;
inputText = resultValue.toString().slice(0, 12);
} catch (error) {
logText = 'Error';
}
updateScreen();
}
// Attach event listeners to each button
document.querySelectorAll('.buttons button').forEach(button => {
button.addEventListener('click', function () {
const buttonValue = this.textContent;
if (buttonValue === '=') {
result();
} else if (buttonValue === '⌫') {
getValue('<');
} else {
getValue(buttonValue);
}
});
});
// Add event listener for keyboard input
document.addEventListener('keydown', function (event) {
const key = event.key;
if (/^[0-9C+\-*/.]$/.test(key) || (key === 'Enter' && inputText !== '')) {
event.preventDefault();
if (key === 'Enter') {
result();
} else if (key === 'Backspace') {
getValue('<');
} else {
getValue(key);
}
}
});
});