-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
87 lines (73 loc) · 2.38 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
let state = {
firstNumber: '',
secondNumber: '',
action: ''
}
// ########################
const output = document.getElementById('output');
// #######################
function addSymbol(target) {
let outputLen = output.innerText.length;
if (outputLen == 13) document.getElementById('output').className = 'calc_top-output-field-min';
if (outputLen == 24) return;
if(/[/*+-]/.test(target)) {
if (state.action && outputLen - 1 == state.firstNumber.length) {
output.innerText = output.innerText.slice(0, outputLen - 1) + target;
} else if (!state.action) {
output.innerText += target;
} else {
equals();
state.firstNumber = output.innerText;
state.secondNumber = '';
output.innerText += target;
}
state.action = target;
return;
}
if (!state.action) {
if (output.innerText == '0') output.innerText = '';
state.firstNumber += target;
} else {
state.secondNumber += target;
}
output.innerText += target;
}
function clearS() {
output.innerText = '0';
state.firstNumber = '';
state.secondNumber = '';
state.action = '';
document.getElementById('output').className = 'calc_top-output-field';
}
function equals() {
switch(state.action) {
case '/': output.innerText = state.firstNumber = (Number(state.firstNumber) / Number(state.secondNumber)).toFixed(4);
break;
case '*': output.innerText = state.firstNumber = Number(state.firstNumber) * Number(state.secondNumber);
break;
case '-': output.innerText = state.firstNumber = Number(state.firstNumber) - Number(state.secondNumber);
break;
case '+': output.innerText = state.firstNumber = Number(state.firstNumber) + Number(state.secondNumber);
break;
}
state.secondNumber = '';
action = '';
}
// #########################
table.onclick = function(event) {
let target = event.target;
if (target.tagName != 'BUTTON') return;
if (/[0-9/*+-]/.test(target.innerText)) {
addSymbol(target.innerText);
}
if (target.innerText == 'C') {
clearS();
}
if(target.innerText == '=') {
equals();
}
if(target.innerText == '←') {
output.innerText = slice(0, output.innerText - 1);
}
}
// ###########################