-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
105 lines (96 loc) · 2.98 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
95
96
97
98
99
100
101
102
103
104
105
class Calulator{
constructor(currScreen,prevScreen){
this.currScreen = currScreen;
this.prevScreen = prevScreen;
this.clear();
}
clear(){
this.currScreen.innerText = '';
this.prevScreen.innerText = '';
this.currOperand = '';
this.prevOperand = '';
this.currOperator = null;
}
appendNumber(number){
if(number === '.' && this.currOperand.includes('.'))
return;
if(number === 'π' && this.currOperand !== '') return;
if(number === 'π')
this.currOperand += Math.PI;
else
this.currOperand += number;
}
chooseOperation(operator){
if(this.currOperand === '') return;
if(this.prevOperand !== ''){
this.compute();
}
this.currOperator = operator;
this.prevOperand = this.currOperand;
this.currOperand = '';
}
compute(){
let computation;
const op = this.currOperator;
const curr = parseFloat(this.currOperand);
const prev = parseFloat(this.prevOperand);
if(isNaN(curr) || isNaN(prev) || op === null) return;
switch(op){
case '+':
computation = prev + curr;
break;
case '-':
computation = prev - curr;
break;
case '÷':
computation = prev / curr;
break;
case '×':
computation = prev * curr;
break;
case '%':
computation = prev % curr;
break;
default:
return;
}
this.currOperand = computation;
this.currOperator = null;
this.prevOperand = '';
}
updateDisplay(){
currScreen.innerText = this.currOperand;
if(this.currOperator !== null){
prevScreen.innerText = `${this.prevOperand} ${this.currOperator}`;
}
else{
prevScreen.innerText = this.prevOperand;
}
}
};
const numberButtons = document.querySelectorAll('.num');
const operatorButtons = document.querySelectorAll('.op');
const equalButton = document.querySelector('.equals');
const deleteButton = document.querySelector('.del');
const prevScreen = document.querySelector('.prev-screen');
const currScreen = document.querySelector('.curr-screen');
const calculator = new Calulator(currScreen,prevScreen);
deleteButton.addEventListener('click', () => {
calculator.clear();
})
numberButtons.forEach(element => {
element.addEventListener('click', () => {
calculator.appendNumber(element.innerText);
calculator.updateDisplay();
})
})
operatorButtons.forEach(element => {
element.addEventListener('click', () => {
calculator.chooseOperation(element.innerText);
calculator.updateDisplay();
})
})
equalButton.addEventListener('click', element => {
calculator.compute();
calculator.updateDisplay();
})