-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
236 lines (213 loc) · 5.62 KB
/
app.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// HTML DOM elements
const buttons = document.querySelector('.buttons');
const buttonsArray = [...buttons.children];
// Calculator variables
let firstOperand = '0';
let secondOperand = '';
let operatorValue = '';
// Math operator functions
function add(num1, num2) {
return num1 + num2;
}
function subtract(num1, num2) {
return num1 - num2;
}
function multiply(num1, num2) {
return num1 * num2;
}
function divide(num1, num2) {
return num1 / num2;
}
// Call correct math operation
function operate(num1, num2, operator) {
const firstNumber = +num1;
const secondNumber = +num2;
let result = 0;
switch (operator) {
case '+':
result = add(firstNumber, secondNumber);
break;
case '-':
result = subtract(firstNumber, secondNumber);
break;
case '*':
result = multiply(firstNumber, secondNumber);
break;
case '/':
if (secondNumber === 0) {
return 'Error';
}
result = divide(firstNumber, secondNumber);
break;
default:
result = 'Please choose correct operator!';
}
return result;
}
function handleButtonClick(event) {
// Get event type and assign value based on it
const buttonValueType = checkEventType(event);
if (!isNaN(buttonValueType)) {
setOperand(buttonValueType);
} else if (['+', '-', '*', '/'].includes(buttonValueType)) {
setOperator(buttonValueType);
} else if (['=', 'Enter'].includes(buttonValueType)) {
evaluate();
} else if (['ac', 'Delete'].includes(buttonValueType)) {
clearAll();
} else if (['del', 'Backspace'].includes(buttonValueType)) {
deleteLastNumber();
} else if (['.', ','].includes(buttonValueType)) {
addDecimalPoint();
}
}
// Check for click or keyup
function checkEventType(event) {
// Remove focus from the last input
event.target.blur();
// Return value based on event type
if (event.type === 'click') {
return event.target.dataset.value;
} else if ((event.type = 'keyup')) {
return event.key;
}
}
// Assign first operand
function setOperand(operand) {
// Set limit to how long can first operand be
if (firstOperand.length >= 16) return;
if (firstOperand === '0') {
firstOperand = operand;
} else {
firstOperand += operand;
}
updateDisplay(firstOperand);
}
// Assign operator
function setOperator(operator) {
// Assign operator only if either of operands are empty
if (firstOperand === '' || secondOperand === '') {
operatorValue = operator;
}
// Handle the case where second operand it not assigned yet
if (secondOperand === '') {
secondOperand = firstOperand;
firstOperand = '';
}
// Handle the case where both operands are assigned and operator clicked again
if (firstOperand !== '' && secondOperand !== '') {
// If errors exists in evaluations process cancel history display update
if (evaluate()) {
operatorValue = operator;
} else {
return;
}
}
updateHistoryDisplay(`${secondOperand} ${operatorValue}`);
}
// Evaluate
function evaluate() {
// Cancel out if user clicks equal on empty first operand
if (firstOperand === '') return false;
let sum;
// If second operand it not empty call operate
if (secondOperand !== '') {
sum = operate(secondOperand, firstOperand, operatorValue);
// If sum error return
if (checkEvaluationResult(sum)) return false;
sum = roundNumber(sum);
updateDisplay(sum);
updateHistoryDisplay(`${secondOperand} ${operatorValue} ${firstOperand} =`);
secondOperand = sum;
firstOperand = '';
return true;
}
}
// Check if math operation returns number or not
function checkEvaluationResult(value) {
if (isNaN(value)) {
updateHistoryDisplay();
updateDisplay("Hey Brainiac you can't divide by zero.");
disableButtons();
return true;
} else {
return false;
}
}
// Update sum display
function updateDisplay(value) {
const display = document.querySelector('.sum');
display.textContent = value;
}
// Update history display
function updateHistoryDisplay(value = '') {
const display = document.querySelector('.history');
display.textContent = value;
}
// Disable all buttons except AC
function disableButtons() {
buttonsArray.forEach((button) => {
if (button.dataset.value !== 'ac') {
button.classList.add('disabled');
}
});
}
// Enable all buttons
function enableButtons() {
buttonsArray.forEach((button) => {
if (button.classList.contains('disabled')) {
button.classList.remove('disabled');
}
});
}
// Clear all
function clearAll() {
firstOperand = '0';
secondOperand = '';
operatorValue = '';
updateDisplay(firstOperand);
updateHistoryDisplay();
enableButtons();
}
// Delete last number
function deleteLastNumber() {
// Both conditions return true only if operate has return a value
if (firstOperand === '' && operatorValue !== '') {
// Clear out history display
updateHistoryDisplay('');
return;
}
// Default value of first operand returns same value
if (firstOperand === '0') return firstOperand;
// Single digit returns default value
if (firstOperand.length === 1) {
firstOperand = '0';
}
// Slice last digit out and reassign back to variable
if (firstOperand.length > 1) {
firstOperand = firstOperand.substring(0, firstOperand.length - 1);
}
updateDisplay(firstOperand);
}
// Input decimal point
function addDecimalPoint() {
if (!firstOperand.includes('.') && firstOperand !== '') {
firstOperand += '.';
updateDisplay(firstOperand);
}
if (firstOperand === '' && !firstOperand.includes('.')) {
firstOperand = '0.';
updateDisplay(firstOperand);
}
}
// Round number to max of 4 decimal places
function roundNumber(number) {
if (Number.isInteger(number)) {
return number;
} else {
return parseFloat(number.toFixed(4));
}
}
// Event listener
buttons.addEventListener('click', handleButtonClick);
document.addEventListener('keyup', handleButtonClick);