-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
97 lines (89 loc) · 2.51 KB
/
script.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
'use strict';
const input = document.querySelector('input');
const numbers = document.querySelectorAll('.number');
const operators = document.querySelectorAll('.operator');
let formula = '';
let tmp = '';
let flag = false;
let reset = false;
numbers.forEach(item => {
item.onclick = () => {
if (reset && flag) {
reset = false;
flag = false;
formula += input.value + tmp;
tmp = '';
input.value = item.textContent;
} else if ((!(flag) && (input.value === '0')) || reset) {
reset = false;
input.value = item.textContent;
} else {
if (flag) {
formula += input.value + tmp;
tmp = '';
input.value = item.textContent;
flag = false;
} else {
input.value += item.textContent;
}
}
if (input.value.split('.')[0] === '') {
input.value = '0' + input.value;
}
if (input.value.split('.').length === 3) {
input.value = input.value.slice(0, -1);
}
};
});
operators.forEach(item => {
item.onclick = () => {
flag = true;
operators.forEach(op => {
op.classList.remove('selected');
});
switch (item.dataset.operator) {
case 'addition':
tmp = '+';
break;
case 'subtraction':
tmp = '-';
break;
case 'multiplication':
tmp = '*';
break;
case 'division':
tmp = '/'
break;
case 'percent':
break;
case 'equal':
input.value = eval(formula + input.value);
formula = '';
tmp = '';
flag = false;
reset = true;
break;
}
if (item.dataset.operator !== 'equal') {
item.classList.add('selected');
}
if (input.value === '0') {
flag = false;
tmp = '';
item.classList.remove('selected');
}
};
});
document.querySelector('.plus_or_minus').onclick = () => {
input.value = eval(input.value) * -1;
};
document.querySelector('.percent').onclick = () => {
input.value = eval(input.value) * 0.01;
};
document.querySelector('.all_clear').onclick = () => {
formula = '';
tmp = '';
flag = false;
reset = false;
input.value = '0';
};