Dia 44/2019 - Calculadora Simples

Desafio #92daysofcode que fiz no final de 2019. Nesse artigo temos o dia 44, mostrando a construção de calculadora simples.

Pré-visualização

Código

Começamos com a estrutura do HTML.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Day 44</title>
<style>
*, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing:border-box; }
html { -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box; font-size: 62.5%; }
* { margin: 0; padding: 0; list-style: none; outline: none; }
body { background: #000; color: #fff; font-family: Arial, Helvetica, sans-serif; }
.container { margin: 60px auto; max-width: 992px; width: 100%; }
</style>
<link rel="stylesheet" type="text/css" href="./day-44.css">
</head>
<body>
<div class="container">
<!-- calculator -->
</div>
<script src="./day-44.js"></script>
</body>
</html>
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
<div class="row">
<ul data-js="results" class="items"></ul>
<div class="calculator">
<div data-js="display" class="display">0</div>
<div class="buttons">
<div class="row">
<button data-js="clear" class="button dark" value="C/E" >C/E</button>
<button data-js="backspace" class="button dark" value="&larr;" >&larr;</button>
<button data-js="plusMinus" class="button" value="-/+" >-/+</button>
<button data-js="operator" class="button" value="/" >&divide;</button>
</div>
<div class="row">
<button data-js="int" class="button" value="7" >7</button>
<button data-js="int" class="button" value="8" >8</button>
<button data-js="int" class="button" value="9" >9</button>
<button data-js="operator" class="button" value="*" >&times;</button>
</div>
<div class="row">
<button data-js="int" class="button" value="4" >4</button>
<button data-js="int" class="button" value="5" >5</button>
<button data-js="int" class="button" value="6" >6</button>
<button data-js="operator" class="button" value="-" >-</button>
</div>
<div class="row">
<button data-js="int" class="button" value="1" >1</button>
<button data-js="int" class="button" value="2" >2</button>
<button data-js="int" class="button" value="3" >3</button>
<button data-js="operator" class="button" value="+" >+</button>
</div>
<div class="row">
<button data-js="int" class="button zero" value="0" >0</button>
<button data-js="decimal" class="button" value="." >.</button>
<button data-js="equal" class="button equal" value="=" >=</button>
</div>
</div>
</div>
</div>
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
.row { align-items: flex-start; display: flex; flex-direction: row; justify-content: space-between; width: 100%;  }

.calculator {
background: #470772;
border-radius: 4px;
border: 2px solid #c222ba;
font-size: 1.2rem;
margin: 0;
padding: 20px;
width: 49%;
}

.display {
background: #fff;
border-radius: 4px;
color: #2f2f2f;
height: 50px;
line-height: 50px;
margin: 0 auto 8px;
padding: 0 10px;
font-size: 3rem;
text-shadow: 1px 1px 0px #fff;
text-align: right;
width: 98%;
}

.button {
font-size: 1.4rem;
padding: 14px;
background: #360457;
border: none;
border-radius: 4px;
color: #fff;
cursor: pointer;
margin: 1.25%;
text-shadow: -1px -1px rgba(0, 0, 0, 0.3);
width: 22.7%;
}

.dark { background: #200333; }
.zero { width: 48%; }
.equal { background: #dfdfdf; color: #333; }

/* result */
.items {
background: #fff;
border-radius: 4px;
max-height: 440px;
overflow-y: scroll;
float: right;
margin: 0;
position: relative;
width: 49%;
}

.item {
background: #fff;
border-bottom: 1px solid #ccc;
color: #333;
display: flex;
flex-direction: row;
font-size: 1.2rem;
justify-content: space-between;
height: 40px;
line-height: 40px;
width: 100%;
}

.item .equation,
.item .answer { display: inline-block; line-height: 40px; padding: 0 10px; }

.item .answer { background: #777; min-width: 30%; }
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
class Calculator {
constructor() {
this.step1 = 0;
this.step2 = 0;
this.isStep1 = true;
this.isStep2 = false;
this.operator = null;
this.answer = 0;
this.step1First = true;
this.step2First = true;
this.isSubmission = false;
this.softSub = false;

this.$display = document.querySelector('[data-js="display"]');
this.$equal = document.querySelector('[data-js="equal"]');

this.$clear = document.querySelector('[data-js="clear"]');
this.$back = document.querySelector('[data-js="backspace"]');
this.$plusMinus = document.querySelector('[data-js="plusMinus"]');

this.$results = document.querySelector('[data-js="results"]');

this.handlers();
}

addOperator(x) {
return x === '*' ? '×' : x === '/' ? '÷' : x;
}

changeDisplay(num) {
this.$display.textContent = this.$display.textContent + num;
}

setDisplay(x) {
this.$display.textContent = this.addOperator(x);
}

setStep1(num) {
if ( this.isStep1 ) {
if ( num === '.' && this.step1.toString().indexOf('.') !== -1 ) {
num = '';
} else if ( num === '.' && this.step1First ) {
num = '0.';
}

if ( this.step1First === true ) {
if ( num === '0' ) {
num = '';
} else {
this.setDisplay(num);
this.step1First = false;
}
} else {
this.changeDisplay(num);
}

this.step1 = this.$display.textContent;

console.log(`step1 = ${this.step1}`);
}
}

setStep2(num) {
if ( !this.isStep1 ) {
if ( num === '.' && this.step2.toString().indexOf('.') !== -1 ) {
num = '';
} else if ( num === '.' && this.step2First ) {
num = '0.';
}

if ( this.step2First === true ) {
if ( num === '0' ) {
num = '';
} else {
this.setDisplay(num);
this.step2First = false;
}
} else {
this.changeDisplay(num);
}

this.step2 = this.$display.textContent;

console.log(`step2 = ${this.step2}`);
}
}

setOperator(op) {
if ( this.isSubmission ) {
this.step1 = this.$display.textContent;
this.step2 = 0;
this.answer = 0;
this.isSubmission = false;
this.setDisplay(step1);
}

if ( !this.step2First ) {
this.handleSoftSubmit();
}

this.setDisplay(op);
this.operator = op;

if ( this.isStep1 ) { this.isStep1 = false; }
if ( !this.isStep2 ) { this.isStep2 = true; }

console.log(`operator = ${this.operator}`);
}

getOperation(operatorString, a, b) {
switch(operatorString) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
}

handleSoftSubmit() {
const preCalc = this.getOperation(this.operator, this.step1, this.step2);
this.answer = parseFloat(preCalc.toPrecision(12));

this.$display.textContent = this.answer;

this.step2First = true;

this.newResult(this.step1, this.operator, this.step2, this.answer);

console.log(this.step1 + ' ' + this.operator + ' ' + this.step2 + ' = ' + this.answer);

this.step1 = this.answer;
this.step2 = 0;
this.operator = this.operator;

this.setDisplay(this.operator);
this.isStep1 = false;
this.isStep2 = true;

this.step2First = true;

this.softSub = true;
}

handleSubmit() {
if ( this.step2First === false ) {
const preCalc = this.getOperation(this.operator, this.step1, this.step2);

this.answer = parseFloat(preCalc.toPrecision(12));

this.$display.textContent = this.answer;
this.isSubmission = true;
this.step2First = true;

this.newResult(this.step1, this.operator, this.step2, this.answer);

console.log(this.step1 + ' ' + this.operator + ' ' + this.step2 + ' = ' + this.answer);
}
}

handlePlusMinus() {
this.$display.textContent = this.$display.textContent * -1;
if ( this.isSubmission ) {
this.step1 = this.step1 * -1;
} else {
if ( this.isStep1 ) {
this.step1 = this.step1 * -1;
this.setDisplay(this.step1);
} else {
this.step2 = this.step2 * -1;
this.setDisplay(this.step2);
}
}
}

handleReset() {
this.step1 = 0;
this.step2 = 0;
this.operator = null;
this.answer = 0;
this.isStep1 = true;
this.isStep2 = false;
this.step1First = true;
this.step2First = true;
this.isSubmission = false;
this.softSub = false;
this.$display.textContent = 0;

this.setDisplay(0);
}

handleBackspace() {
if ( this.$display.textContent !== '' && this.$display.textContent !== '0' ) {
this.$display.textContent = this.$display.textContent.substring(0, this.$display.textContent.length - 1);
if ( this.isStep1 === true ) {
this.step1 = parseFloat(this.step1.toString().substring(0, this.step1.toString().length - 1 ));
} else {
this.step2 = parseFloat(this.step2.toString().substring(0, this.step2.toString().length - 1 ));
}
}
}

newResult(step1, operator, step2, answer) {
const result = document.createElement("li");
result.className = 'item';
result.innerHTML = `
<span class="equation">${step1} ${this.addOperator(operator)} ${step2}</span>
<span class="answer">${answer}</span>
`;
this.$results.insertBefore(result, this.$results.firstChild);
}

handlers() {
this.$equal.addEventListener('click', () => {
this.handleSubmit();
});

this.$clear.addEventListener('click', () => {
this.handleReset();
});

this.$plusMinus.addEventListener('click', () => {
this.handlePlusMinus();
});

this.$back.addEventListener('click', () => {
this.handleBackspace();
});

const loop = (selector, fn) => {
const elements = document.querySelectorAll(selector);
for (let i = 0; i < elements.length; i++) {
fn(elements[i], i);
}
}

loop('[data-js="int"], [data-js="decimal"]', element => {
element.addEventListener('click', event => {
const value = event.target.value;
if ( this.isSubmission === false ) {
if ( this.isStep1 === true ) {
this.setStep1(value);
} else {
this.setStep2(value);
}
} else {
this.handleReset();
this.setStep1(value);
}
});
});

loop('[data-js="operator"]', element => {
element.addEventListener('click', event => {
const value = event.target.value;
this.setOperator(value);
});
});
}
}


new Calculator();

Conclusão

A postagem original pode ser vista no meu Instagram e o código está acessível no meu Github.

Relacionados

Ao fechar este aviso ou continuar navegando no site Nerd Calistênico, você aceita o uso de cookies.

Este site usa cookies para assegurar a melhor experiência para os nossos usuários. Consulte nossa política de privacidade.

Uma nova versão está disponível. Clique aqui para atualizar.