-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
108 lines (88 loc) · 2.39 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
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
102
103
104
105
106
107
108
let display = document.getElementById('display');
document.addEventListener('keydown', handleKeyPress);
const darkModeOptions = {
bottom: '90%', // Adjusted position
right: '20px',
left: 'unset',
time: '0.5s',
mixColor: '#fff',
backgroundColor: '#fff',
buttonColorDark: '#100f2c',
buttonColorLight: '#fff',
saveInCookies: true,
label: '🌓',
autoMatchOsTheme: true
};
const darkmode = new Darkmode(darkModeOptions);
darkmode.showWidget();
function handleKeyPress(event) {
const key = event.key;
if (isNumericKey(key) || isOperatorKey(key) || key === '.') {
appendToDisplay(key);
} else if (key === 'Enter') {
calculateResult();
} else if (key === 'Escape') {
clearDisplay();
} else if (key === 'Backspace') {
deleteLastCharacter();
}
}
function appendToDisplay(value) {
if (display.value.length < 15) {
display.value += value;
animateButtonPress();
}
}
function animateButtonPress() {
display.classList.add('button-press');
setTimeout(() => {
display.classList.remove('button-press');
}, 100);
}
function clearDisplay() {
display.value = '';
}
function deleteLastCharacter() {
display.value = display.value.slice(0, -1);
}
// Toggle the sign of the current number
function toggleSign() {
display.value = parseFloat(display.value) * -1;
}
function toggleNegation() {
toggleSign();
}
function calculatePercentage() {
display.value = parseFloat(display.value) / 100;
}
function calculateResult() {
try {
let result = evaluateExpression(display.value);
if (!isValidNumber(result)) {
throw new Error('Invalid result: Please check your input');
}
display.value = formatResult(result);
} catch (error) {
display.value = `Error: ${error.message}`;
}
}
function isValidNumber(num) {
return typeof num === 'number' && isFinite(num) && !isNaN(num);
}
function formatResult(result) {
const roundedResult = Math.round(result * 10000000000) / 10000000000;
return roundedResult.toString();
}
function isNumericKey(key) {
return !isNaN(key);
}
function isOperatorKey(key) {
return ['+', '-', '*', '/'].includes(key);
}
function evaluateExpression(expression) {
try {
return math.evaluate(expression);
} catch (error) {
throw new Error('Invalid expression');
}
}