/
Stack.js
161 lines (143 loc) · 3.39 KB
/
Stack.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
class Stack {
constructor() {
this.data = []
this.peek = 0
}
isEmpty() {
return this.peek === 0
}
push(element) {
this.data[this.peek] = element
this.peek += 1
}
pop() {
if (this.isEmpty() === false) {
this.peek -= 1
return this.data.pop()
}
}
top() {
return this.data[this.peek - 1]
}
}
function isOperand(char) {
return !isNaN(char)
}
function isOperator(char) {
switch (char) {
case '+': return true
case '-': return true
case '*': return true
case '%': return true
case '/': return true
case '(': return true
}
return false
}
function inPrec(char) {
switch(char) {
case '+':
case '-':
return 2
case '*':
case '%':
case '/':
return 4
case '(':
return 0
}
}
function outPrec(char) {
switch(char) {
case '+':
case '-':
return 1
case '*':
case '%':
case '/':
return 3
case '(':
return 100
}
}
function inToPost(input) {
let stack = new Stack()
let postfix = []
for (let i = 0; i < input.length; i++) {
if (isOperand(input[i])) {
postfix.push(input[i])
} else if (isOperator(input[i])) {
if (stack.isEmpty() || outPrec(input[i]) > inPrec(stack.top())) {
stack.push(input[i])
} else {
while (!stack.isEmpty() && outPrec(input[i]) < inPrec(stack.top())) {
postfix.push(stack.top())
stack.pop()
}
stack.push(input[i])
}
} else if (input[i] === ')') {
while (stack.top() != '(') {
postfix.push(stack.top())
stack.pop()
if (stack.isEmpty()) {
console.log('Wrong input')
return
}
}
stack.pop()
}
}
while (!stack.isEmpty()) {
if (stack.top() === '(') {
console.log('Wrong input')
return
}
postfix.push(stack.top())
stack.pop()
}
return postfix
}
function evaluatePostfix(exp) {
let stack = new Stack()
for (let i = 0; i < exp.length; i++) {
console.log(stack.data)
if (isOperand(exp[i])) {
// + converts, string into an integer type
console.log(exp[i])
console.log(isOperand(exp[i]))
stack.push(+exp[i])
}
else {
const valOne = stack.pop()
const valTwo = stack.pop()
switch(exp[i]) {
case '+':
stack.push(valTwo + valOne)
break
case '-':
stack.push(valTwo - valOne)
break
case '*':
stack.push(valTwo * valOne)
break
case '/':
stack.push(valTwo / valOne)
}
}
}
return stack.pop()
}
function spaceSeparator(string) {
return string.split(/([-()+*/])/g)
}
module.exports = {
Stack,
inToPost,
outPrec,
inPrec,
isOperator,
isOperand,
spaceSeparator,
evaluatePostfix
}