Skip to content

Instantly share code, notes, and snippets.

@kimmking
Created September 20, 2018 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimmking/b80d59829ede802cc12bde56f528f788 to your computer and use it in GitHub Desktop.
Save kimmking/b80d59829ede802cc12bde56f528f788 to your computer and use it in GitHub Desktop.
expression-eval.js
var evalRPN = function(tokens) {
var stack = [];
while(tokens.length > 0){
var c = tokens.shift();
if(c == "+"){
c = add(stack);
}else if(c == "-"){
c = sub(stack);
}else if(c == "*"){
c = mul(stack);
}else if(c == "/"){
c = div(stack);
}
stack.push(c);
// console.log("tokens="+tokens);
// console.log("stack="+stack);
}
return stack[0];
};
var add = function(arr) {
var a2 = arr.pop();
var a1 = arr.pop();
return a2+a1;
}
var sub = function(arr) {
var a2 = arr.pop();
var a1 = arr.pop();
return a1-a2;
}
var mul = function(arr) {
var a2 = arr.pop();
var a1 = arr.pop();
return a2*a1;
}
var div = function(arr) {
var a2 = arr.pop();
var a1 = arr.pop();
return a1/a2;
}
var prior = function(s){
if(s == "+" || s == "-" ) return 0;
if(s == "*" || s == "/" ) return 1;
return -1;
}
var proc = function(expr,v){
if(v.length>0){
expr.push(parseInt(v));
}
return "";
}
var calculate = function(str) {
var expr = [];
var opr = [];
var v = "";
for(var i in str){
var s=str[i];
if(s != " ") {
if(s == "("){
opr.push(s);
v=proc(expr,v);
}else if(s == "+" || s == "-" || s == "*" || s == "/"){
// v=proc(expr,v);
// opr.push(s);
// }else if(s == "+" || s == "-"){
v=proc(expr,v);
var p = opr[opr.length-1];
while(prior(s)<=prior(p)){
expr.push(opr.pop());
p = opr[opr.length-1];
}
opr.push(s);
}else if(s == ")"){
v=proc(expr,v);
var t = opr.pop();
while (t!="(") {
expr.push(t);
t = opr.pop();
}
}else{
v=v+s;
}
}
// console.log("expr="+expr);
// console.log("opr="+opr);
}
while (opr.length>0) {
expr.push(opr.pop());
}
// console.log("str="+str);
// console.log("expr="+expr);
return evalRPN(expr);
};
var ex = "(110/2+(14+25*2+2)*3-103)+(16+80-7)";
console.log(ex+"="+calculate(ex));
ex = "( 130/5+(119/7- (15*3*4/5-5*3)+20*5)-3)+(62+108)";
console.log(ex+"="+calculate(ex));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment