-
Notifications
You must be signed in to change notification settings - Fork 6
/
calculator.js
44 lines (35 loc) · 1.24 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
let displayValue = '';
let ans = '0';
function appendToDisplay(value) {
displayValue += value;
document.getElementById('display').value = displayValue;
}
function clearDisplay() {
displayValue = '';
document.getElementById('display').value = '';
}
function popFromDisplay() {
// Remove the last character from the display value.
displayValue = displayValue.substring(0, displayValue.length - 1);
// Set the display value to the updated string.
document.getElementById('display').value = displayValue;
}
function calculateResult() {
try {
// Replace the `eval()` function with the `Math` object.
displayValue = displayValue.replace('^', '**');
displayValue = displayValue.replace('ln', 'Math.log');
displayValue = displayValue.replace('√', 'Math.sqrt');
// Evaluate the display value using the `eval()` function.
displayValue = eval(displayValue);
document.getElementById('display').value = displayValue;
ans = displayValue;
} catch (error) {
displayValue = 'Error';
document.getElementById('display').value = displayValue;
}
}
function previousValue() {
displayValue += ans.toString();
document.getElementById('display').value = displayValue;
}