-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
275 lines (253 loc) · 7.83 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
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
document.addEventListener('DOMContentLoaded', function() {
//Variables
let num1 = '';
let num2 = '';
let operator = '';
let currentOperator = '';
let result = '';
let equation = '';
let lastActionValidCalculation = false;
const validEquation = /^(-?(0|[1-9]\d*)(\.\d*)?)\s*([\+\-\*\/])\s*(-?(0|[1-9]\d*)(\.\d*)?)$/;
//DOM Elements
const output = document.getElementById('output');
output.innerText = '0';
//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;
};
function performOperation(operator, num1, num2) {
switch (operator) {
case '+':
return add(parseFloat(num1), parseFloat(num2));
case '-':
return subtract(parseFloat(num1), parseFloat(num2));
case '*':
return multiply(parseFloat(num1), parseFloat(num2));
case '/':
return divide(parseFloat(num1), parseFloat(num2));
}
};
function parseEquation(input) {
const lastChar = input.trim().slice(-1);
if (['+', '-', '*', '/'].includes(lastChar)) {
input = input.trim().slice(0, -1);
}
const regex = /^(?<firstNumber>-?\d+\.?\d*)\s*(?<operator>[\+\-\*\/])\s*(?<secondNumber>-?\d+\.?\d*)$/;
const match = input.match(regex);
if (match) {
num1 = match.groups.firstNumber;
num2 = match.groups.secondNumber;
operator = match.groups.operator
}
if (checkForDivisionByZero(num2, operator)) {
clearAll();
return;
}
result = performOperation(operator, num1, num2);
if (String(result).includes('.')) {
let roundedResult = Math.round(result * 10) / 10;
return output.innerText = roundedResult;
}
output.innerText = result;
equation = '';
};
function checkForDivisionByZero(y, operator) {
if (operator === '/' && y === '0') {
alert("Division by zero is not allowed.\nPlease enter a valid divisor.");
return true;
}
return false;
};
function isValidEquation(testEquation) {
return validEquation.test(testEquation);
};
function validateEquation(equation) {
if (isValidEquation(equation)) {
lastActionValidCalculation = true;
}
};
function calculateResultIfValid(calculate) {
if(lastActionValidCalculation) {
parseEquation(equation);
output.innerText = Math.round(result * 10) / 10 + currentOperator;
lastActionValidCalculation = false;
}
};
function setInitialInput(buttonValue) {
output.innerText = buttonValue;
equation = buttonValue;
currentOperator = buttonValue;
};
function addToCurrentInput(buttonValue) {
output.innerText += buttonValue;
equation += buttonValue;
currentOperator = buttonValue;
};
function togglePlusMinusSign() {
if (output.innerText.includes('-', 0)) {
let str = output.innerText;
let arr = Array.from(str).slice(1).join('');
output.innerText = arr;
return output.innerText;
} else if (output.innerText === '0') {
output.innerText = '-';
} else {
let str = output.innerText;
let arr = Array.from(str);
let addToArr = arr.unshift('-');
let revertedString = arr.join('');
output.innerText = revertedString;
return output.innerText;
}
};
function handleNumberButtonClick(event) {
let buttonValue = event.target.innerText;
if (output.innerText === '0' && buttonValue === '.') {
output.innerText = '0.';
return;
}
output.innerText === '0' ?
setInitialInput(buttonValue) :
addToCurrentInput(buttonValue);
validateEquation(equation);
};
function handleOperatorButtonClick(event) {
let buttonValue = event.target.innerText;
if (checkForDivisionByZero(num2, operator)) {
clearAll();
return;
}
addToCurrentInput(buttonValue);
validateEquation(equation);
calculateResultIfValid(output.innerText);
equation = output.innerText;
buttonDot.removeAttribute('disabled');
};
function deleteLastCharacter() {
if (output.innerText.length === 1) {
clearAll();
}
else {
let numberToString = output.innerText.toString();
let deleteLast = numberToString.slice(0, numberToString.length - 1);
output.innerText = deleteLast;
if (['+', '-', '*', '/'].includes(numberToString[numberToString.length - 1])) {
currentOperator = '';
operator = '';
lastActionValidCalculation = false;
}
output.innerText = deleteLast || '0';
equation = deleteLast || '';
}
};
function clearInputButton() {
clearAll();
buttonDot.removeAttribute('disabled')
opBtn.forEach(button => {
button.removeAttribute('disabled');
})
};
function clearAll() {
num1 = '';
num2 = '';
operator = '';
currentOperator = '';
result = '';
equation = '';
lastActionValidCalculation = false;
output.innerText = '0';
}
function equalButton() {
validateEquation(output.innerText)
if (lastActionValidCalculation === true) {
parseEquation(output.innerText);
} else {
clearAll();
alert('This is not a valid equation.\nPlease try again.')
}
opBtn.forEach(button => {
button.removeAttribute('disabled');
})
String(result).includes('.') ? buttonDot.setAttribute('disabled', 'disabled') :
buttonDot.removeAttribute('disabled');
};
//Mouse Event Listeners
//Toggle Plus/Minus
const plusMinusBtn = document.querySelector('.plus-minusBtn');
plusMinusBtn.addEventListener('click', () => {
togglePlusMinusSign();
});
//Number Buttons
const numBtn = document.querySelectorAll('.numBtn');
for ( let i = 0; i < numBtn.length; i++) {
numBtn[i].addEventListener('click', (event) => {
handleNumberButtonClick(event);
})
};
//Operator Buttons
const opBtn = document.querySelectorAll('.opBtn');
for ( let i =0; i <opBtn.length; i++ ) {
opBtn[i].addEventListener('click', (event) => {
handleOperatorButtonClick(event);
})
};
//Clear Input Button
const buttonErase = document.querySelector('.btn-ac');
buttonErase.addEventListener('click', () => {
clearInputButton();
});
//Delete Last Button
const buttonDelete = document.querySelector('.btn-del');
buttonDelete.addEventListener('click', () => {
deleteLastCharacter();
});
// Equal Button
const buttonEqual = document.querySelector('.btnEqual');
buttonEqual.addEventListener('click', () => {
equalButton();
});
//Decimal Button
const buttonDot = document.querySelector('#dot');
buttonDot.addEventListener('click', () => {
buttonDot.setAttribute('disabled', 'disabled');
})
//Keyboard Event Listeners
document.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
key = equalButton();
} else if (event.key === 'NumpadEnter') {
key = equalButton();
} else if (event.key === 'Backspace') {
key = deleteLastCharacter();
} else if (event.key === 'Delete') {
key = clearInputButton();
} else if (event.key === 'Escape') {
key = clearInputButton();
} else if ((event.key >= '0' && event.key <= '9') || event.key === '.') {
if (event.key === '.' && buttonDot.disabled) {
return;
}
if (event.key === '.') {
buttonDot.setAttribute('disabled', 'disabled');
}
handleNumberButtonClick({
target: {innerText : event.key}
});
event.preventDefault();
} else if (['+', '-', '*', '/'].includes(event.key)) {
handleOperatorButtonClick({
target: {innerText : event.key}
});
event.preventDefault();
}
});
});