-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
142 lines (110 loc) · 2.67 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//MATH PART
function add(a,b){
return a+b;
}
function subtract(a,b){
return a-b;
}
function multiply(a,b){
return a*b;
}
function divide(a,b){
return a/b;
}
function operate(a,operator,b){
if(operator=='+'){
return add(a,b);
}
else if(operator=='-'){
return subtract(a,b);
}
else if(operator=='*'){
return multiply(a,b);
}
else if(operator=="/"){
return divide(a,b);
}
}
//DISPLAY CONTROL
let currDisplay=document.querySelector('#curr');
let prevDisplay=document.querySelector('#prev');
let lastResultDisplayed=false;
function onClick(btn){
if(btn.textContent=='='){
prevDisplay.textContent=currDisplay.textContent;
currDisplay.textContent=evalExpr(currDisplay.textContent);
lastResultDisplayed=true;
}
else if(!isOperator(btn.textContent) && lastResultDisplayed){
prevDisplay.textContent=currDisplay.textContent;
currDisplay.textContent=btn.textContent;
lastResultDisplayed=false;
}
else{
currDisplay.textContent+=btn.textContent;
lastResultDisplayed=false;
}
}
//check If car is operator
function isOperator(char){
if(char=='+'||char=='-'||char=='*'||char=='/'){
return true
}
else{
return false;
}
}
//evaluate an expression
function evalExpr(expression){
let num1="";
let num2="";
let operator;
let toggle=false;
for(let i=0;i<expression.length;i++){
if(!isOperator(expression[i])){
if(toggle){
num2+=expression[i];
}
else{
num1+=expression[i];
}
}
else if(isOperator(expression[i])){
toggle = true;
if(num1&&num2&&operator){
num1=parseFloat(num1);
num2=parseFloat(num2);
num1=operate(num1,operator,num2);
num2="";
operator=undefined
}
operator=expression[i];
}
if(i==expression.length-1){
num1=parseFloat(num1);
num2=parseFloat(num2);
num1=operate(num1,operator,num2);
num2="";
}
}
let strCheck=num1.toString();
if(strCheck.includes('.')){
return num1.toFixed(3)
}
else{
return num1;
}
}
let buttons = document.querySelectorAll('.btn');
for(let i=0;i<buttons.length;i++){
buttons[i].addEventListener('click',event=>onClick(event.target));
}
let clearBtn=document.querySelector('#clear');
clearBtn.addEventListener('click',()=>{
currDisplay.textContent='';
prevDisplay.textContent='';
});
let backBtn=document.querySelector('#backSpace');
backBtn.addEventListener('click',()=>{
currDisplay.textContent=currDisplay.textContent.slice(0,-1)
});