-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc.js
84 lines (73 loc) · 1.89 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
const botonNumeros = document.getElementsByName('data-number');
const botonOpera = document.getElementsByName('data-opera');
const botonIgual = document.getElementsByName('data-igual')[0];
const botonDelete = document.getElementsByName('data-delete')[0];
var result = document.getElementById('result');
var opeActual='';
var opeAnterior='';
var operacion = undefined;
botonNumeros.forEach(function(boton) {
boton.addEventListener('click', function(){
agregarNumero(boton.innerText);
})
});
botonOpera.forEach(function(boton){
boton.addEventListener('click', function(){
selectOperacion(boton.innerText);
})
});
botonIgual.addEventListener('click', function(){
calcular();
actualizarDisplay();
});
botonDelete.addEventListener('click', function(){
clear();
actualizarDisplay();
})
function selectOperacion(op){
if(opeActual ==='') return;
if(opeAnterior !==''){
calcular();
}
operacion = op.toString();
opeAnterior = opeActual;
opeActual = '';
}
function calcular(){
var calculo;
const anterior = parseFloat(opeAnterior);
const actual = parseFloat(opeActual);
if(isNaN(anterior) || isNaN(actual)) return;
switch(operacion){
case '+':
calculo = anterior + actual;
break;
case '-':
calculo = anterior - actual;
break;
case 'x':
calculo = anterior * actual;
break;
case '/':
calculo = anterior / actual;
break;
default:
return;
}
opeActual = calculo;
operacion = undefined;
opeAnterior = '';
}
function agregarNumero(num){
opeActual = opeActual.toString() + num.toString();
actualizarDisplay();
}
function actualizarDisplay(){
result.value = opeActual;
}
function clear(){
opeActual = '';
opeAnterior= '';
operacion = undefined;
}
clear();