You can break a string into Tokens easily as follows: If your code for generating Tokens is correct then skip to next code for conversion to postfix form using Shunting yard algorithm.
function Break(expression){ /*Expression is string like "2.22+3-5"*/
var Tokens=[];
//Start at the end of the string//
var i=expression.length-1;
var Operators=['+','-','*','/','^','(',')'];
while(i>=0){
if(Operators.indexOf(expression[i])!=-1 && expression[i]!='-'){
Tokens.push(expression[i]);
i-=1;
}
else if(expression[i]=='-'){
if(i===0){
Tokens.push('neg');
i-=1;
}
else if(expression[i-1]!=')' && Operators.indexOf(expression[i-1])!=-1 ){
Tokens.push('neg');
i-=1;
}
else{
Tokens.push('-');
i-=1;
}
}
else{
var x=0,wt=0;
while(i>=0 && Operators.indexOf(expression[i])==-1){
if(expression[i]=='.'){
x=x/Math.pow(10,wt);
i-=1;
wt=0;
}
else{
x+=Math.floor(expression[i])*Math.pow(10,wt);
wt+=1;
i-=1;
}
}
Tokens.push(x);
}
}
return Tokens.reverse();
}
Once the string is converted into a list of Tokens returned by Break function, Shunting yard algorithm can be used for conversion to postfix form:
Following subroutine returns priorities of operator:
function Priority(x){
switch(x){
case 'neg': /*Highest priority of unary negation operator*/
return 4;
case '^':
return 3;
case '/':
return 2;
case '*':
return 2;
case '+':
return 1;
case '-':
return 1;
case '(':
return 0;
}
}
Finally we are ready for conversion to postfix:
function Postfix(Tokens){
var Stack=[],List=[];
var Operators=['^','/','*','+','-'];
var i;
for(i=0;i<Tokens.length;i++){
if(Operators.indexOf(Tokens[i])!=-1){
while(Stack.length!=-1 && Priority(Stack[Stack.length-1])>=Priority(Tokens[i]))
List.push(Stack.pop());
Stack.push(Tokens[i]);
}
else if(Tokens[i]=='(')
Stack.push(Tokens[i]);
else if(Tokens[i]==')'){
while(Stack[Stack.length-1]!='(')
List.push(Stack.pop());
Stack.pop();
}
else
List.push(Tokens[i]);
}
while(Stack.length!==0)
List.push(Stack.pop());
return List;
}
Now, say, if we want postfix form of "1+1+1" , we call Postfix(Break("1+1+1")). You can have a look at the running code at: http://jsbin.com/AbIleWu/1/edit?js,output
PS: You can add other unary operators like sin,cos,tan,log,ln etc. easily.