-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
331 lines (272 loc) · 8.25 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
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//*---------------------------*/
/*---- INITIALIZE VARIABLES --*/
/*---------------------------*/
const DOMstrings = {
pad: ".pad",
operation: 'operation',
memory: "memory",
displayInput: ".display-input",
clearBtn: ".clear-btn",
memoryInput: ".memory-input"
};
const KeyCodes = {
zero: 48,
eight: 56,
nine: 57,
shift: 16,
equal: 187,
minus: 189,
divide: 191,
period: 190,
clear: 8,
enter: 13
}
const padElement = document.querySelector(DOMstrings.pad);
const clearBtn = document.querySelector(DOMstrings.clearBtn);
const padBtnsCollection = padElement.getElementsByTagName('button');
const padBtnsArr = Array.prototype.slice.call(padBtnsCollection);
let numpadBtnsArr = padBtnsArr.filter((btn) => !btn.classList.contains(DOMstrings.operation) && !btn.classList.contains(DOMstrings.memory));
let operationBtnsArr = padBtnsArr.filter((btn) => btn.classList.contains(DOMstrings.operation));
let memoryBtnsArr = padBtnsArr.filter((btn) => btn.classList.contains(DOMstrings.memory));
let exp1='', exp2='', prevExp=0;
let mathSymbol = null;
let prevKey = 0;
let memorySum = 0;
//*---------------------------*/
/*---- HELPER METHODS ------*/
/*---------------------------*/
const calculate = (num1, symbol, num2) => {
let answer = 0;
switch(symbol){
case '+':
answer = num1 + num2;
break;
case '-':
answer = num1 - num2;
break;
case 'x':
answer = num1 * num2;
break;
case '/':
answer = num1 / num2;
break;
default:
answer = 0;
}
return answer;
}
const updateDisplay = (num) => {
//Cannot show the following characters =
if(Number.isNaN(num)) return;
//Update the clear btn
clearBtn.textContent = num > 0 ? 'C':'CE';
//Update Input element
const displayInputEl = document.querySelector(DOMstrings.displayInput);
displayInputEl.value = num;
}
const resetValues = () => {
mathSymbol = '';
exp1='';
exp2='';
result=0;
prevExp=0;
}
const clearEverything = () => {
resetValues();
updateDisplay(0);
}
const clearCurrentExpression = () => {
if((!mathSymbol && !prevExp) || prevExp) {
exp1 = '';
} else if((mathSymbol && !prevExp) || !prevExp) {
exp2 = '';
}
updateDisplay(0);
}
function isInt(num) {
return num % 1 === 0;
}
const buildExpression = (newInput, exp) => {
//Check we dont go over 10 digits
if(exp.length >= 10) return exp;
//Handle muliple decimals
if(newInput === '.') {
//Check we don't have one already. If we do exit.
if(exp.indexOf(newInput) !== -1) return exp;
//Check that there is a number in front of the decimal.
newInput = exp.length === 0 ? '0.': newInput;
}
//Build expression
exp += newInput;
//Return new expression.
return exp;
}
const buildExpressions = (newInput) => {
if(!mathSymbol) {
//Build expression 1
exp1 = buildExpression(newInput, exp1);
return exp1;
} else {
//Build expression 2
exp2 = buildExpression(newInput, exp2);
return exp2;
}
}
//Formats big numbers into more readable expressions.
const compressNumber = (num, digits=3) => {
if(isInt(num)) {
//Convert to scientific notation
return num.toString().length > 10 ? num.toExponential(digits): num;
} else {
//Make sure the result does not go over 3 points after decimal.
return num.toFixed(digits)/1;
}
}
// Calculates equation and handles repeated evaluations when called in a row.
const evaluateEquation = () => {
if(!exp2) return exp1;
const inputValue = document.querySelector(DOMstrings.displayInput).value;
//Prepare for the second time we evaluate the equation.
if(!prevExp) {
prevExp = exp2;
} else {
exp1 = inputValue;
exp2 = prevExp;
}
//Calculate result
return compressNumber(calculate(+exp1, mathSymbol, +exp2));
}
//*---------------------------*/
/*------- MAIN METHODS ------*/
/*---------------------------*/
// Handles Number Pad Section Logic
const handleNumberPad = (newInput) => {
let displayValue = '';
if(newInput === '=') {
displayValue = evaluateEquation();
} else if(prevExp) {
resetValues();
}
if(newInput !== '=') {
displayValue = buildExpressions(newInput);
}
//Display result
updateDisplay(displayValue);
}
const handleKeyboardNumberPad = (keyCode) => {
if((keyCode >= KeyCodes.zero && keyCode <= KeyCodes.nine) && prevKey !== KeyCodes.shift) {
handleNumberPad(String.fromCharCode(keyCode));
}
//Period Sign
if(keyCode === KeyCodes.period && prevKey !== KeyCodes.shift) {
handleNumberPad('.');
}
//Equal Sign
if(((prevKey !== KeyCodes.shift) && (keyCode === KeyCodes.equal)) || (keyCode === KeyCodes.enter)) {
handleNumberPad('=');
}
}
// Handles Math Operations Section Logic
const handleOperationsPad = (newInput) => {
const inputValue = document.querySelector(DOMstrings.displayInput).value;
if(prevExp) resetValues();
if(inputValue && !exp1) exp1 = inputValue;
if(exp1 && exp2 && mathSymbol) {
exp1 = compressNumber(calculate(+exp1, mathSymbol, +exp2));
exp2 = '';
updateDisplay(exp1);
}
mathSymbol = newInput;
}
const handleKeyboardOperationsPad = (keyCode) => {
//Add
if((prevKey === KeyCodes.shift) && (keyCode === KeyCodes.equal)) {
console.log('+');
handleOperationsPad('+');
}
//Subtract
if(keyCode === KeyCodes.minus) {
console.log('-');
handleOperationsPad('-');
}
//Multiply
if((prevKey === KeyCodes.shift) && (keyCode === KeyCodes.eight)) {
console.log('*');
handleOperationsPad('x');
}
//Divide
if(keyCode === KeyCodes.divide) {
console.log('/');
handleOperationsPad('/');
}
}
const handleClearDisplay = () => {
if(clearBtn.textContent === 'CE') {
clearEverything();
} else {
clearCurrentExpression();
clearBtn.textContent = 'CE';
}
}
const handleKeyboardClearDisplay = (keyCode) => {
if(keyCode === KeyCodes.clear) {
handleClearDisplay();
}
}
/*---------------------------*/
/*---- EVENT LISTENERS ------*/
/*---------------------------*/
clearBtn.addEventListener("click", handleClearDisplay);
//Number Pad Event Listener
numpadBtnsArr.forEach((btn) => {
btn.addEventListener('click', (event) => handleNumberPad(event.target.textContent));
});
//Operations Pad Event Listener
operationBtnsArr.forEach((btn => {
btn.addEventListener('click', (event) => handleOperationsPad(event.target.textContent));
}));
//Keyboard Event Listener
document.addEventListener('keydown', (event) => {
let keyCode = event.keyCode;
//Numbers Pad
handleKeyboardNumberPad(keyCode);
//Operations Pad
handleKeyboardOperationsPad(keyCode);
//Clear Btn
handleKeyboardClearDisplay(keyCode);
prevKey = keyCode;
});
//Memory Pad Event Listener
memoryBtnsArr.forEach((btn) => {
btn.addEventListener('click', (event) => {
const memoryInput = document.querySelector(DOMstrings.memoryInput);
const memoryBtn = event.target.textContent;
let result = 0;
switch(memoryBtn) {
case 'MC':
memorySum = 0;
break;
case 'MR':
if(!mathSymbol) {
exp1=memorySum;
} else {
exp2=memorySum;
}
updateDisplay(memorySum);
break;
case 'M+':
result = +document.querySelector(DOMstrings.displayInput).value;
memorySum += result;
memorySum = compressNumber(memorySum);
break;
case 'M-':
result = +document.querySelector(DOMstrings.displayInput).value;
memorySum += (-1 * result);
memorySum = compressNumber(memorySum);
break;
default:
console.log("Something went wrong, memory btn does not exist");
}
memoryInput.value = `MEM: ${memorySum}`;
});
})