-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
77 lines (65 loc) · 2.43 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
const buttons = document.querySelectorAll('button');
const display = document.querySelector('.display');
let expression = '';
buttons.forEach(function(button) {
button.addEventListener('click', function () {
let buttonValue = button.textContent;
if (buttonValue === '=') {
const result = evaluateExpression(expression);
console.log(result);
if (!isFinite(result)) {
displayError('Division by zero');
} else {
display.textContent = result;
}
expression = '';
} else if(buttonValue === 'C') {
clearDisplay();
} else {
expression += buttonValue;
display.textContent += buttonValue;
}
});
});
function evaluateExpression(expr) {
//These are for the possibility of handling parantheses and exponantiation.
// expr = expr.replace(/\s+/g, '');
// // Evaluate parentheses first
// while (expr.includes('(')) {
// expr = expr.replace(/\(([^()]+)\)/g, function(match, innerExpr) {
// return evaluateExpression(innerExpr);
// });
// }
// // Evaluate exponentiation
// while (expr.includes('^')) {
// expr = expr.replace(/(-?\d+(?:\.\d+)?)\^(-?\d+(?:\.\d+)?)/g, function(match, base, exponent) {
// return Math.pow(parseFloat(base), parseFloat(exponent));
// });
// }
while (expr.includes('*') || expr.includes('/')) {
expr = expr.replace(/(-?\d+(?:\.\d+)?)\s*([\/*])\s*(-?\d+(?:\.\d+)?)/g, function(match, operand1, operator, operand2) {
if (operator === '*') {
return parseFloat(operand1) * parseFloat(operand2);
} else if (operator === '/') {
return parseFloat(operand1) / parseFloat(operand2);
}
});
}
while (expr.includes('+') || expr.includes('-')) {
expr = expr.replace(/(-?\d+(?:\.\d+)?)\s*([\+\-])\s*(-?\d+(?:\.\d+)?)/g, function(match, operand1, operator, operand2) {
if (operator === '+') {
return parseFloat(operand1) + parseFloat(operand2);
} else if (operator === '-') {
return parseFloat(operand1) - parseFloat(operand2);
}
});
}
return expr;
}
function displayError(message) {
display.textContent = 'Error: ' + message;
}
function clearDisplay() {
display.textContent = '';
expression = '';
}