-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
78 lines (64 loc) · 2.3 KB
/
script.js
File metadata and controls
78 lines (64 loc) · 2.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
document.addEventListener('DOMContentLoaded', function () {
const display = document.getElementById('display');
const buttons = document.querySelectorAll('button');
function updateDisplay(text) {
display.value += text;
}
function handleNumberClick(number) {
updateDisplay(number);
}
function handleOperatorClick(operator) {
updateDisplay(operator);
}
function handleCalculateClick() {
try {
let expression = display.value;
// Replace '×' with '*' for multiplication
expression = expression.replace(/×/g, '*');
// Replace (a)(b) with (a*b)
expression = expression.replace(/\((\d+)\)\((\d+)\)/g, '($1*$2)');
// Replace (a)b with (a*b)
expression = expression.replace(/\((\d+)\)(\d+)/g, '($1*$2)');
// Replace (expression)(expression) with (expression*expression)
expression = expression.replace(/\(([^)]+)\)\(([^)]+)\)/g, '($1*$2)');
// Replace (expression)expression with (expression*expression)
expression = expression.replace(/\(([^)]+)\)([^)]+)/g, '($1*$2)');
const result = evaluateExpression(expression);
display.value = result;
} catch (error) {
display.value = 'Error';
}
}
function handleClearClick() {
display.value = '';
}
function handleDeleteClick() {
display.value = display.value.slice(0, -1);
}
function evaluateExpression(expression) {
// Evaluate the expression using the eval function
return eval(expression);
}
buttons.forEach(function (button) {
button.addEventListener('click', function () {
const action = button.getAttribute('data-action');
if (action === 'append') {
const text = button.textContent;
handleNumberClick(text);
} else if (action === 'add' || action === 'subtract' || action === 'multiply' || action === 'divide') {
const operator = button.textContent;
handleOperatorClick(operator);
} else if (action === 'calculate') {
handleCalculateClick();
} else if (action === 'clear') {
handleClearClick();
} else if (action === 'delete') {
handleDeleteClick();
} else if (action === 'open-parenthesis') {
updateDisplay('(');
} else if (action === 'close-parenthesis') {
updateDisplay(')');
}
});
});
});