-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathcalculator_logic.js
107 lines (97 loc) · 2.68 KB
/
calculator_logic.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
let currentInput = '0';
let currentOperation = null;
let previousInput = null;
function updateDisplay() {
document.getElementById('display').textContent = currentInput;
}
function appendNumber(number) {
if (currentInput === '0' && number !== '.') {
currentInput = number;
} else {
currentInput += number;
}
updateDisplay();
}
function appendSymbol(symbol) {
if (currentInput === '0') {
currentInput = symbol;
} else {
currentInput += symbol;
}
updateDisplay();
}
function setOperation(op) {
if (currentOperation !== null) {
calculateResult();
}
previousInput = currentInput;
currentInput = '0';
currentOperation = op;
updateDisplay();
}
function clearCalculator() {
currentInput = '0';
currentOperation = null;
previousInput = null;
updateDisplay();
}
function calculateResult() {
if (currentOperation === null) {
return;
}
let body = {};
if (['add', 'subtract', 'multiply', 'divide'].includes(currentOperation)) {
body = {
operation: currentOperation,
a: parseFloat(previousInput),
b: parseFloat(currentInput)
};
} else if (['derivative', 'integral', 'solve', 'expand', 'factor'].includes(currentOperation)) {
body = {
operation: currentOperation,
expression: currentInput
};
}
fetch('/calculate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
.then(response => response.json())
.then(data => {
if (data.error) {
currentInput = 'Error';
} else {
currentInput = data.result.toString();
}
currentOperation = null;
previousInput = null;
updateDisplay();
})
.catch(error => {
console.error('Error:', error);
currentInput = 'Error';
updateDisplay();
});
}
document.addEventListener('keydown', (event) => {
if (event.key >= '0' && event.key <= '9' || event.key === '.') {
appendNumber(event.key);
} else if (event.key === '+') {
setOperation('add');
} else if (event.key === '-') {
setOperation('subtract');
} else if (event.key === '*') {
setOperation('multiply');
} else if (event.key === '/') {
setOperation('divide');
} else if (event.key === 'Enter' || event.key === '=') {
calculateResult();
} else if (event.key === 'Escape') {
clearCalculator();
} else if (event.key === 'x' || event.key === '(' || event.key === ')' || event.key === '^') {
appendSymbol(event.key);
}
});