-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
106 lines (101 loc) · 2.12 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
var num1 = "";
var nStack = [];
var opStack = [];
var op = "";
var invalid = false;
var precedence = {"+":1,"-":1,"*":2,"/":2};
function reset(){
$("#result").fadeIn(1000,function(){
$("#result").text("0");
num1 = "";
op = "";
nStack = [];
opStack = [];
invalid = false;
});
}
$("#clear").click(reset);
$(".num").click(function(){
num1 += $(this).text();
$("#result").text(num1);
});
function operate(num1, num2, op){
switch(op){
case "+":
return Number(num1)+Number(num2);
case "-":
return Number(num2)-Number(num1);
case "*":
return Number(num1)*Number(num2);
case "/":
return Number(num2)/Number(num1);
}
return num1;
}
$(".op").click(function(){
op = $(this).text();
console.log(op);
if(num1.length!=0)
nStack.push(num1);
if(nStack.length == opStack.length+1){
if(opStack.length == 0){
if(op!="=")
opStack.push(op);
else{
$("#result").text(num1);
}
}
else{
if(op!="="){
while(opStack.length!=0 && precedence[opStack[opStack.length-1]]>=precedence[op]){
if(nStack.length>=2){
var t1 = nStack[nStack.length-1];
nStack.pop();
var t2 = nStack[nStack.length-1];
nStack.pop();
t1 = operate(t1,t2,opStack[opStack.length-1]);
console.log("operation "+t1);
opStack.pop();
nStack.push(t1);
}
else{
$("#result").text("Invalid operation");
invalid = true;
$("#result").fadeOut(1000,reset);
break;
}
}
if(!invalid)
opStack.push(op);
}
else{
while(opStack.length!=0){
if(nStack.length>=2){
var t1 = nStack[nStack.length-1];
nStack.pop();
var t2 = nStack[nStack.length-1];
nStack.pop();
t1 = operate(t1,t2,opStack[opStack.length-1]);
opStack.pop();
nStack.push(t1);
}
else{
$("#result").text("Invalid operation");
invalid = true;
$("#result").fadeOut(1000,reset);
break;
}
}
if(!invalid)
$("#result").text(t1);
}
}
num1 = "";
}
else{
$("#result").text("Invalid operation");
$("#result").fadeOut(1000,reset);
}
console.log("nstack "+nStack);
console.log("opStack "+opStack);
});