-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculatorscript.js
112 lines (97 loc) · 2.37 KB
/
calculatorscript.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
105
106
107
108
109
110
111
112
const display = document.getElementById('display');
const buttons = document.querySelectorAll('.button');
let currInput = '';
let prevInput = '';
let operator = null;
let displayOp = false;
buttons.forEach(button => {
button.addEventListener('click', function() {
const value = this.innerText;
const action = this.getAttribute('data-action');
if (!action) {
appendNumber(value);
} else if (action === 'add') {
chooseOperation('+');
} else if (action === 'subtract') {
chooseOperation('-');
} else if (action === 'multiply') {
chooseOperation('*');
} else if (action === 'divide') {
chooseOperation('/');
} else if (action === 'equals') {
compute();
} else if (action === 'clear') {
clear();
} else if (action === 'clear-entry') {
clearEntry();
} else if (action === 'delete') {
deleteNumber();
}
});
});
function appendNumber(number) {
if (currInput.includes('.') && number === '.') return;
currInput = currInput.toString() + number.toString();
displayOp = false;
updateDisplay();
}
function chooseOperation(op) {
if (currInput === '') return;
if (prevInput !== '') {
compute();
}
operator = op;
prevInput = currInput;
currInput = '';
displayOp = true;
updateDisplay();
}
function compute() {
let result;
const prev = parseFloat(prevInput);
const curr = parseFloat(currInput);
if (isNaN(prev) || isNaN(curr)) return;
switch (operator) {
case '+':
result = prev + curr;
break;
case '-':
result = prev - curr;
break;
case '*':
result = prev * curr;
break;
case '/':
result = prev / curr;
break;
default:
return;
}
currInput = result;
operator = undefined;
prevInput = '';
displayOp = true;
updateDisplay();
}
function updateDisplay() {
if (displayOp && operator) {
display.innerText = prevInput + ' ' + operator;
} else {
display.innerText = currInput || '0';
}
}
function clear() {
currInput = '';
prevInput = '';
operator = undefined;
displayOp = false;
updateDisplay();
}
function clearEntry() {
currInput = '';
updateDisplay();
}
function deleteNumber() {
currInput = currInput.toString().slice(0, -1);
updateDisplay();
}