-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc.js
97 lines (87 loc) · 2.26 KB
/
calc.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
const display = document.querySelector('.display');
const calc = document.querySelector('.calculator-body');
let currentCalculation = '0';
let sum = 0;
let lastOperation; // save last operation used by user to apply calculations
// refresh the screen when user has clicked a button
function refresh() {
display.innerText = currentCalculation;
}
// apply operator selected by user to be save
function applyOperation(currentCalculationInt) {
if (lastOperation === '÷') {
sum /= currentCalculationInt;
} else if (lastOperation === '×') {
sum *= currentCalculationInt;
} else if (lastOperation === '-') {
sum -= currentCalculationInt;
} else {
sum += currentCalculationInt;
}
}
function calculate(value) {
if (currentCalculation === '0') {
return; // nothing to do
}
const currentCalculationInt = parseInt(currentCalculation); // create and convert existing user input into integers to do calculations
if (sum !== 0) {
applyOperation(currentCalculationInt);
} else {
sum = currentCalculationInt;
}
lastOperation = value;
currentCalculation = '0';
}
function number(value) {
if (currentCalculation !== '0') {
currentCalculation += value;
} else {
currentCalculation = value;
}
}
// handle the maths by what operation the user has selected
function operation(value) {
switch (value) {
case '÷':
case '×':
case '-':
case '+':
calculate(value);
break;
case 'C':
currentCalculation = '0';
sum = 0;
break;
case '=':
if (lastOperation === null) {
return; // nothing to calculate
}
applyOperation(parseInt(currentCalculation));
lastOperation = null;
currentCalculation = +sum;
sum = 0;
break;
case '←':
if (currentCalculation.length === 1) {
currentCalculation = '0';
} else {
currentCalculation = currentCalculation.substring(0, currentCalculation.length - 1);
}
break;
default:
break;
}
}
// capture button event values
function click(value) {
if (!Number.isNaN(parseInt(value))) {
number(value);
} else {
operation(value);
}
refresh();
}
// attach event listener on all buttons
calc.addEventListener('click', function(e) {
click(e.target.innerText);
});