-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
89 lines (83 loc) · 2.94 KB
/
script.js
File metadata and controls
89 lines (83 loc) · 2.94 KB
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
const displayCurrent = document.getElementById('current');
const displayHistory = document.getElementById('history');
let currentInput = '';
let historyInput = '';
let operator = '';
const buttons = document.querySelectorAll('.btn');
buttons.forEach(button => {
button.addEventListener('click', () => {
const num = button.getAttribute('data-num');
const func = button.getAttribute('data-func');
const oper = button.getAttribute('data-operator');
//koi number ka input ka button ka code
if (num) {
currentInput += num;
displayCurrent.textContent = currentInput;
}
//normal function button ka
if (func) {
if (func === 'clear') {
currentInput = '';
historyInput = '';
operator = '';
displayCurrent.textContent = '0';
displayHistory.textContent = '';
} else if (func === 'backspace') {
currentInput = currentInput.slice(0, -1);
displayCurrent.textContent = currentInput || '0';
} else if (func === 'calculate') {
if (currentInput && operator && historyInput) {
calculateResult();
}
} else if (func === '.') {
if (!currentInput.includes('.')) {
currentInput += '.';
displayCurrent.textContent = currentInput;
}
}
}
//operation ka button ka part
if (oper) {
if (currentInput) {
if (historyInput && operator) {
calculateResult();
}
operator = oper;
historyInput = currentInput;
currentInput = '';
displayHistory.textContent = historyInput + ' ' + getOperatorSymbol(operator);
displayCurrent.textContent = '';
}
}
});
});
function getOperatorSymbol(oper) {
switch (oper) {
case '+': return '+';
case '-': return '-';
case '*': return '×';
case '/': return '÷';
case 'sqrt': return '√';
case 'exp': return 'EXP';
default: return '';
}
}
function calculateResult() {
let result;
const num1 = parseFloat(historyInput);
const num2 = parseFloat(currentInput);
switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
case 'sqrt': result = Math.sqrt(num1); break;
case 'exp': result = Math.pow(num1, num2); break;
default: result = 'Error'; break;
}
displayCurrent.textContent = result;
historyInput = '';
currentInput = result.toString();
operator = '';
displayHistory.textContent = '';
}