-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
99 lines (96 loc) · 2.58 KB
/
app.js
File metadata and controls
99 lines (96 loc) · 2.58 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
90
91
92
93
94
95
96
97
98
99
let btns=document.querySelectorAll(".box");
let n="";
let symbols=["+","-","*","/"];
let commands=["CE","DEL"];
let computeStack=[];
let refreshDisp=true;
let res=null;
let prevNumber=null;
function operate(){
res=(computeStack.pop());
res=res.includes(".")?parseFloat(res):parseInt(res);
let symbol=computeStack.pop();
let number=computeStack.pop();
number=number.includes(".")?parseFloat(number):parseInt(number);
if (symbol =="+")
res=res+number;
if(symbol=="-")
res=number-res;
if(symbol=="*")
res=res*number;
if(symbol=="/")
res=number/res;
console.log(res);
computeStack.push(res.toString());
}
function displayRes(){
var disp=document.querySelector(".disp");
disp.textContent=res.toString();
prevNumber=res.toString();
}
function resetDisp(){
var disp=document.querySelector(".disp");
disp.textContent="0";
for(let i=0;i<computeStack.length;i++)
computeStack.pop();
}
function addElement(ip){
if(ip=="."){
if( computeStack.length!=0 &&
!symbols.includes(computeStack[computeStack.length-1]) &&
!computeStack[computeStack.length-1].includes(".")
)
{
dispValue=computeStack.pop()+ip;
computeStack.push(dispValue);
var disp=document.querySelector(".disp");
disp.textContent=dispValue;
prevNumber=dispValue;
}
}
else if (ip=="CE"){
resetDisp();
}
else if(ip=="="){
if(computeStack.length>2){
operate();
displayRes();
}
}
else if (symbols.includes(ip)){
if(computeStack.length>2)
{
operate();
displayRes();
}
if (symbols.includes(computeStack[computeStack.length-1])){
computeStack.push(prevNumber);
operate();
displayRes();
}
computeStack.push(ip);
}
else if(commands.includes(ip))
{
console.log("command detected");
}
else{
let dispValue=null;
if(computeStack.length==0 || symbols.includes(computeStack[computeStack.length-1])){
computeStack.push(ip);
dispValue=ip;
}
else{
dispValue=computeStack.pop()+ip;
computeStack.push(dispValue);
}
var disp=document.querySelector(".disp");
disp.textContent=dispValue;
prevNumber=dispValue;
}
}
btns.forEach((btn)=>{
btn.addEventListener('click',()=>{
addElement(btn.textContent);
})
})