-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
105 lines (86 loc) · 2.87 KB
/
main.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
98
99
100
101
102
103
104
let operator = '';
let previousValue = '';
let currentValue = '';
let previousScreen = document.querySelector('.previous');
let currentScreen = document.querySelector('.current');
document.addEventListener('DOMContentLoaded', function() {
//Store all components on HTML in our JS
let clear = document.querySelector('#clear-btn');
let equal = document.querySelector('.equal');
let decimal = document.querySelector('.decimal');
let numbers = document.querySelectorAll('.number');
let operators = document.querySelectorAll('.operator');
let previousScreen = document.querySelector('.previous');
let currentScreen = document.querySelector('.current');
numbers.forEach((number) => number.addEventListener('click', (e) => {
handleNumber(e.target.textContent)
currentScreen.textContent = currentValue;
}))
operators.forEach((op) => op.addEventListener('click', (e) => {
handleOperator(e.target.textContent)
previousScreen.textContent = previousValue + ' ' + operator;
currentScreen.textContent = currentValue;
}))
clear.addEventListener('click', () => {
previousValue = '';
currentValue = '';
operator = '';
previousScreen.textContent = currentValue;
currentScreen.textContent = currentValue;
})
equal.addEventListener('click', () => {
if (currentValue != '' && previousValue != '') {
calculate();
previousScreen.textContent = '';
if (previousValue.length <= 10) {
currentScreen.textContent = previousValue;
} else {
currentScreen.textContent = previousValue.slice(0, 10) + '...';
}
}
})
decimal.addEventListener('click', () => {
addDecimal();
})
})
function handleNumber(num) {
if (currentValue.length <= 10) {
currentValue += num;
}
}
function handleOperator(op) {
operator = op;
previousValue = currentValue;
currentValue = '';
}
function clearCal() {
previousValue = '';
currentValue = '';
operator = '';
previousScreen.textContent = previousValue;
currentScreen.textContent = currentValue;
}
function calculate() {
previousValue = Number(previousValue);
currentValue = Number(currentValue);
if (operator === '+') {
previousValue += currentValue;
} else if (operator === '-') {
previousValue -= currentValue;
} else if (operator === 'X') {
previousValue *= currentValue;
} else if (operator === '/') {
previousValue /= currentValue;
}
previousValue = roundNumber(previousValue);
previousValue = previousValue.toString();
currentValue = previousValue.toString();
}
function roundNumber(num) {
return Math.round(num * 1000) / 1000;
}
function addDecimal() {
if (!currentValue.includes('.')) {
currentValue += '.';
}
}