-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
89 lines (73 loc) · 2.22 KB
/
index.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
const display_before = document.getElementById('value_before');
const display_actual = document.getElementById('value_actual');
const number_bottons = document.querySelectorAll('.number');
const operator_bottons = document.querySelectorAll('.operator');
class Calculator {
sum(num1, num2) {
return num1 + num2;
}
subtraction(num1, num2) {
return num1 - num2;
}
multiply(num1, num2) {
return num1 * num2;
}
divide(num1, num2) {
return num1 / num2;
}
}
class Display {
constructor(display_before, display_actual) {
this.display_actual = display_actual;
this.display_before = display_before;
this.caculator = new Calculator();
this.typeOperation = undefined;
this.valueActual = '';
this.valueBefore = '';
this.signos = {
sum: '+',
subtraction: '-',
divide: '%',
multiply: 'x',
};
}
delete() {
this.valueActual = this.valueActual.toString().slice(0, -1);
this.printValue();
}
deleteAll() {
this.valueActual = '';
this.valueBefore = '';
this.typeOperation = undefined;
this.printValue();
}
computar(type1) {
this.typeOperation !== 'same' && this.calculate();
this.typeOperation = type1;
this.valueBefore = this.valueActual || this.valueBefore;
this.valueActual = '';
this.printValue();
}
addNumber(number) {
if (number === '.' && this.valueActual.includes('.')) return;
this.valueActual = this.valueActual.toString() + number.toString();
this.printValue();
}
printValue() {
this.display_actual.textContent = this.valueActual;
this.display_before.textContent = `${this.valueBefore} ${this.signos[this.typeOperation] || ''}`;
}
calculate() {
const valueBefore = parseFloat(this.valueBefore);
const valueActual = parseFloat(this.valueActual);
if (isNaN(valueActual) || isNaN(valueBefore)) return;
this.valueActual = this.caculator[this.typeOperation](valueBefore, valueActual);
}
}
const display = new Display(display_before, display_actual);
number_bottons.forEach(boton => {
boton.addEventListener('click', () => display.addNumber(boton.innerHTML));
});
operator_bottons.forEach(boton => {
boton.addEventListener('click', () => display.computar(boton.value));
});