Created
December 4, 2014 15:00
-
-
Save cdragos/840471197e8d82735057 to your computer and use it in GitHub Desktop.
Arithmetic Parsing Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var expr = '(2-2)-0+7+2-(3)-(3-(6-5))-4'; | |
function peek(stack) { | |
return stack[stack.length - 1]; | |
} | |
function Token(value) { | |
var op = { | |
'+': { | |
'prec': 1, | |
'func': function (x, y) { return x + y; } | |
}, | |
'-': { | |
'prec': 1, | |
'func': function (x, y) { return x - y; } | |
}, | |
'*': { | |
'prec': 2, | |
'func': function (x, y) { return x * y; } | |
}, | |
'/': { | |
'prec': 2, | |
'func': function (x, y) { return x / y; } | |
} | |
}; | |
this.value = value; | |
this.isNumber = function () { | |
return !isNaN(parseInt(this.value, 10)); | |
}; | |
this.isOperator = function () { | |
return op[this.value] !== undefined; | |
}; | |
this.isParentheses = function () { | |
return ['(', ')'].indexOf(this.value) >= 0; | |
}; | |
this.isHigerPrec = function (op_other) { | |
return (op[this.value] && op[op_other] && | |
(op[this.value].prec >= op[op_other].prec)); | |
}; | |
this.isLeftParantheses = function () { | |
return this.value === '('; | |
}; | |
this.isRightParantheses = function () { | |
return this.value === ')'; | |
}; | |
this.result = function (x, y) { | |
return op[this.value].func(x, y); | |
}; | |
return this; | |
} | |
function infixToPostfix(expr) { | |
var stack = [], | |
output = ''; | |
for (var i = 0, token; i < expr.length; i++) { | |
token = Token(expr[i]); | |
if (token.isNumber()) { | |
output += token.value + ' '; | |
} | |
if (token.isOperator()) { | |
while(stack.length > 0 && token.isHigerPrec(peek(stack))) { | |
output += stack.pop() + ' '; | |
} | |
stack.push(token.value); | |
} | |
if (token.isParentheses()) { | |
if(token.isLeftParantheses()) { | |
stack.push(token.value); | |
} | |
if(token.isRightParantheses()) { | |
while(!Token(peek(stack)).isLeftParantheses()) { | |
output += stack.pop() + ' '; | |
} | |
stack.pop(); | |
} | |
} | |
} | |
while (stack.length > 0) { | |
output += stack.pop() + ' '; | |
} | |
return output.replace(/\s+$/,''); | |
} | |
function evalPostfix(expr) { | |
var stack = []; | |
for (var i = 0, token, x, y; i < expr.length; i++) { | |
token = Token(expr[i]); | |
if(token.isNumber()) { | |
stack.push(parseInt(token.value, 10)); | |
} | |
if(token.isOperator()) { | |
y = stack.pop(); | |
x = stack.pop(); | |
stack.push(token.result(x, y)); | |
} | |
} | |
return stack[0]; | |
} | |
function compute_expression(expr) { | |
postfix_expr = infixToPostfix(expr); | |
console.log(evalPostfix(postfix_expr)); | |
} | |
compute_expression(expr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment