-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
70 lines (61 loc) · 1.93 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
const display = document.querySelector('.display');
const previous = document.querySelector('.previous');
const nums = document.querySelectorAll('.num');
const operands = document.querySelectorAll('.operand');
const equalBtn = document.querySelector('.equal');
const resetBtn = document.querySelector('.reset');
const deleteBtn = document.querySelector('.del');
const pointBtn = document.querySelector('.point');
nums.forEach((i) => {
i.addEventListener('click', function () {
display.innerHTML += i.value;
});
});
const operand = function () {
display.innerHTML += this.value;
if (
display.innerHTML.startsWith('+') ||
display.innerHTML.startsWith('/') ||
display.innerHTML.startsWith('*')
) {
display.innerHTML = '';
}
previous.innerHTML = display.innerHTML;
display.innerHTML = '';
};
const equal = function () {
const numberOne = parseFloat(previous.innerHTML);
const numberTwo = parseFloat(display.innerHTML);
let num;
if (previous.innerHTML.endsWith('+')) {
num = (numberOne * 10 + numberTwo * 10) / 10;
display.innerHTML = num;
} else if (previous.innerHTML.endsWith('-')) {
display.innerHTML = numberOne - numberTwo;
} else if (previous.innerHTML.endsWith('/')) {
display.innerHTML = numberOne / numberTwo;
if (numberTwo === 0) {
display.innerHTML = 'Err';
}
} else if (previous.innerHTML.endsWith('*')) {
display.innerHTML = numberOne * numberTwo;
}
previous.innerHTML = '';
};
const addPoint = () => {
display.innerHTML += '.';
};
const clear = () => {
display.innerHTML = '';
previous.innerHTML = '';
};
const deleteLast = () => {
display.innerHTML = display.innerHTML.slice(0, -1);
};
operands.forEach((op) => {
op.addEventListener('click', operand);
});
equalBtn.addEventListener('click', equal);
resetBtn.addEventListener('click', clear);
deleteBtn.addEventListener('click', deleteLast);
pointBtn.addEventListener('click', addPoint);