const MAX = 40;
class Stack {
constructor() {
this
.st = Array(MAX).fill(0);
this
.top = 0;
}
push(value) {
this
.top += 1;
this
.st[
this
.top] = value;
}
pop() {
let topval =
this
.st[
this
.top];
this
.top -= 1;
return
topval;
}
gettop() {
return
this
.top;
}
}
class Express {
constructor(ptr) {
this
.s =
new
Stack();
this
.pStr = ptr;
this
.len =
this
.pStr.length;
}
parse() {
let lastval = 0;
let lastop = 0;
for
(let j = 0; j <
this
.len; j++) {
let ch =
this
.pStr[j];
if
(ch >= '0
' && ch <= '
9
') {
this.s.push(parseInt(ch) - parseInt('
0
'));
}
// If it'
s an operator
else
if
(ch ==
'+'
|| ch ==
'-'
|| ch ==
'*'
|| ch ==
'/'
) {
if
(
this
.s.gettop() == 1) {
this
.s.push(ch);
}
else
{
lastval =
this
.s.pop();
lastop =
this
.s.pop();
if
((ch ==
'*'
|| ch ==
'/'
) && (lastop ==
'+'
|| lastop ==
'-'
)) {
this
.s.push(lastop);
this
.s.push(lastval);
}
else
{
if
(lastop ==
'+'
) {
this
.s.push(
this
.s.pop() + lastval);
}
else
if
(lastop ==
'-'
) {
this
.s.push(
this
.s.pop() - lastval);
}
else
if
(lastop ==
'*'
) {
this
.s.push(
this
.s.pop() * lastval);
}
else
if
(lastop ==
'/'
) {
this
.s.push(
this
.s.pop() / lastval);
}
else
{
console.log(
"\nUnknown operator"
);
process.exit(1);
}
}
this
.s.push(ch);
}
}
else
{
console.log(
"\nUnknown input character"
);
process.exit(1);
}
}
}
solve() {
let lastval = 0;
while
(
this
.s.gettop() > 1) {
lastval =
this
.s.pop();
let lastop =
this
.s.pop();
if
(lastop ==
'+'
) {
this
.s.push(
this
.s.pop() + lastval);
}
else
if
(lastop ==
'-'
) {
this
.s.push(
this
.s.pop() - lastval);
}
else
if
(lastop ==
'*'
) {
this
.s.push(
this
.s.pop() * lastval);
}
else
if
(lastop ==
'/'
) {
this
.s.push(
this
.s.pop() / lastval);
}
else
{
console.log(
"\nUnknown operator"
);
process.exit(1);
}
}
return
parseInt(
this
.s.pop());
}
}
let st;
st =
"2+3*4/3-2"
;
let eptr =
new
Express(st);
eptr.parse();
console.log(eptr.solve());