-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
94 lines (78 loc) · 2.41 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
const $numOperations = [...document.querySelectorAll('.numbers, .operation')];
const $clearButton = document.querySelector('.clear');
const $calculateButton = document.querySelector('.equal');
const $signButton = document.querySelector('.sign');
const $commaButton = document.querySelector('.comma');
const $percentageButton = document.querySelector('.persent');
const $input = document.querySelector('#input');
let result = ""
let freeze = ""
$clearButton.addEventListener('click', clearResult)
$calculateButton.addEventListener('click', calculateResult)
$signButton.addEventListener('click', changeSign)
$commaButton.addEventListener('click', addComma)
$percentageButton.addEventListener('click', convertToPercentage)
function convertToPercentage() {
const num = +$input.value.replace(/,/g, '.')
if (!isNaN(num)) $input.value = `${num * 100}%`
}
function addComma() {
$input.value += ','
result += '.'
}
function changeSign() {
const num = +$input.value;
if (isNaN(num)) {
$input.value = `-(${$input.value})`
result = `-(${result})`
} else {
$input.value = `${-num}`
result = `${-num}`
}
}
function clearResult() {
freeze = false;
result = ""
$input.value = "0"
}
$numOperations.forEach(($numOperations) => {
$numOperations.addEventListener('click', handleButtonClick)
})
function handleButtonClick(event) {
if (freeze) {
event.preventDefault()
return
}
let value = event.target.innerText;
if (value === "=") {
return
}
if ($input.value === 0 && value === 0) {
return
}
if (result.length === 0) {
$input.value = ""
}
const operators = ['÷', '×', '-', '+']
if (operators.includes(result[result.length - 1]) && operators.includes(value)) {
$input.value = $input.value.replace(/.$/, value)
result = $input.value.replace(/.$/, value)
return
}
result += value
$input.value += value;
}
function calculateResult() {
try {
result = result.replace(/×/g, '*').replace(/÷/g, '/');
$input.value = `${eval(result)}`.replace(/\./g, ',')
// freeze = true
} catch (e) {
$input.value = "Error"
setTimeout(() => {
if (confirm("Error!")) {
clearResult()
}
}, 0)
}
}