-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
122 lines (101 loc) · 2.72 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
let firstNumber = {
storedCheck: false,
};
let secondNumber;
let operator;
let operatorClicked = false;
let displayText;
let MAX = 11;
const display = document.querySelector('#display');
const numberButtons = document.querySelectorAll('.number-btn');
const operatorButtons = document.querySelectorAll('.operator-btn');
const clear = document.querySelector('#clear');
// operation functions
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
function multiply(x, y) {
return x * y;
};
function divide(x, y) {
return x / y;
}
function operate(sign, x, y) {
switch (sign) {
case ('+'):
return add(+x, +y);
break;
case ('-'):
return subtract(+x, +y);
break;
case ('*'):
return multiply(+x, +y);
break;
case ('/'):
return divide(+x, +y);
break;
case ('='):
return x;
break;
}
}
// const equalButton = document.querySelector('=');
function populateDisplay(digit) {
displayText = display.textContent;
if (displayText.length < MAX) {
display.textContent += digit;
}
}
function storeDisplay() {
return display.textContent;
}
function clearDisplay() {
display.textContent = "";
}
function resetApp() {
clearDisplay();
firstNumber.number = null;
firstNumber.storedCheck= false;
secondNumber = null;
operator = null;
operatorClicked = false;
}
clear.addEventListener('click', resetApp);
numberButtons.forEach(button => {
button.addEventListener('click', () => {
if (operatorClicked) {
clearDisplay();
populateDisplay(button.value);
}
else {
populateDisplay(button.value);
}
operatorClicked = false;
});
});
operatorButtons.forEach(button => {
displayText = display.textContent;
button.addEventListener('click', () => {
if (!operatorClicked) {
if (!firstNumber.storedCheck) {
firstNumber.number = storeDisplay();
firstNumber.storedCheck ^= true;
}
else if (firstNumber.storedCheck) {
secondNumber = storeDisplay();
firstNumber.number = operate(operator, firstNumber.number, secondNumber);
if (firstNumber['number'].toString().length <= MAX) {
display.textContent = firstNumber.number;
}
else {
display.textContent = firstNumber['number'].toExponential(5);
}
}
}
operator = button.value;
operatorClicked = true;
});
});