Please login or register. Welcome to the Studio, guest!


Quick Links:


newBookmarkLockedFalling

Eric

Eric Avatar



1,442


November 2005
function ReverseExpression(expr)
{
this.origexpr = expr;
this.expr = expr.replace(/\s+/g, '');
}
ReverseExpression.numberExp = /^(-?\d*\.?\d+)$/;
ReverseExpression.operators = '+-*/^';
ReverseExpression.prototype.compute = function()
{
while(this.expr.match(/(\(([^\(]+)\))/))
{
sub_expr = new ReverseExpression(RegExp.$2);
this.expr = this.expr.replace(RegExp.$1, sub_expr.subCompute());
}
return this.subCompute();
}
ReverseExpression.prototype.subCompute = function()
{
this.add();
this.subtract();
this.multiply();
this.divide();
this.exp();
return this.expr * 1;
}
ReverseExpression.prototype.findValues = function(loc)
{
var values = new Array();
for(var num1 = loc - 1; num1 >= 0 && this.expr.substring(num1, loc).match(ReverseExpression.numberExp); num1--);
if(ReverseExpression.operators.indexOf(this.expr.charAt(num1)) == -1 && this.expr.charAt(++num1) == '-')
num1++;
values[0] = this.expr.substring(num1, loc++);
for(var num2 = loc + 1; num2 <= this.expr.length && this.expr.substring(loc, num2).match(ReverseExpression.numberExp); num2++);
values[1] = this.expr.substring(loc, --num2);
return values;
}
ReverseExpression.prototype.add = function()
{
var loc;
while((loc = this.expr.indexOf('+')) != -1)
{
var vals = this.findValues(loc);
this.expr = this.expr.substring(0, loc - vals[0].length) + ((vals[0]*1 + vals[1]*1) + '') + this.expr.substring(loc + vals[1].length + 1, this.expr.length);
}
}
ReverseExpression.prototype.subtract = function()
{
var loc;
while((loc = this.expr.indexOf('-')) != -1)
{
var vals = this.findValues(loc);
this.expr = this.expr.substring(0, loc - vals[0].length) + ((vals[0]*1 - vals[1]*1) + '') + this.expr.substring(loc + vals[1].length + 1, this.expr.length);
}
}
ReverseExpression.prototype.multiply = function()
{
var loc;
while((loc = this.expr.indexOf('*')) != -1)
{
var vals = this.findValues(loc);
this.expr = this.expr.substring(0, loc - vals[0].length) + (((vals[0]*1) * (vals[1]*1)) + '') + this.expr.substring(loc + vals[1].length + 1, this.expr.length);
}
}
ReverseExpression.prototype.divide = function()
{
var loc;
while((loc = this.expr.indexOf('/')) != -1)
{
var vals = this.findValues(loc);
this.expr = this.expr.substring(0, loc - vals[0].length) + (((vals[0]*1) / (vals[1]*1)) + '') + this.expr.substring(loc + vals[1].length + 1, this.expr.length);
}
}
ReverseExpression.prototype.exp = function()
{
var loc;
while((loc = this.expr.indexOf('^')) != -1)
{
var vals = this.findValues(loc);
this.expr = this.expr.substring(0, loc - vals[0].length) + (Math.pow(vals[0]*1, vals[1]*1) + '') + this.expr.substring(loc + vals[1].length + 1, this.expr.length);
}
}



Example:
var x = new ReverseExpression('5+(5*8)');
document.write(x.compute() + "<br />");



For all of your reverse order of operation needs.


Last Edit: Sept 1, 2008 21:03:28 GMT by Eric

newBookmarkLockedFalling