Reputation: 555
I am trying to build a calculator in javascript but I am stuck and don't know how to proceed. every time someone click on 1 + 1 / 2, for exemple I am creating an array that pushes everything that was typed so in the case above the array would be
[1, "+", 1, "/", 2];
However, I can't figure it out how to transform this array into an actual mathematical value. I had an idea of looping through all elements like this:
for(var i=0; i<arrayCharacters.length ;i++){
if(arrayCharacters[i] != "*" || arrayCharacters[i] != "/" || arrayCharacters[i] != "+" || arrayCharacters[i] != "*"){
arrayNumbers.push(arrayCharacters.slice(0, i));
console.log(arrayNumbers);
}
}
It's very incomplete because I got stuck. Can anyone help me?
Upvotes: 0
Views: 591
Reputation: 138234
var result=eval(arrayCharacters.join(""));
You could also parse the expression manually, however this requires building up a tree, as math isnt evaluated left to right.
If you really want to parse it on your own (which is far better then eval), you could use a math notation that really goes from left to right , so its much easier to parse ( As @Scott suggested). An implementation:
var stack=[];
var arrayCharacters=[1,2,"/",1,"+"];
for(var i=0;i<arrayCharacters.length;i++){
var char=arrayCharacters[i];
if(typeof char==="number"){
stack.push(char);
continue;
}
var op2=stack.pop()||0;
var op1=stack.pop()||0;
var res;
if(char=="+"){
res=op1+op2;
}
if(char=="-"){
res=op1-op2;
}
if(char=="*"){
res=op1*op2;
}
if(char=="/"){
res=op1/op2;
}
stack.push(res);
}
var result=stack.pop();
Math Syntax (RPN (1)):
1+2 => 1 2 +
1/2+3 => 1 2 / 3 +
1+2/3 => 1 2 3 / +
(1+2)/3 => 1 2 + 3 /
1/2/3+4/5/6 => 1 2 / 3 / 4 5 / 6 / +
http://jsbin.com/zofeqitiba/edit?console
Upvotes: 4
Reputation: 1572
"eval" function is a very good choice in your case. Also you can use the math.js library, which comes with a powerful expression parser.
Upvotes: 1