0

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?

4
  • meta.stackoverflow.com/questions/284236/… Commented Jun 26, 2017 at 17:35
  • You have to come up with your own interpretation of +, -, /, *.. operators. Commented Jun 26, 2017 at 17:36
  • Or just eval.. but this is not clean IMO Commented Jun 26, 2017 at 17:36
  • 1
    Instead of inserting sequentially, you can try looking at RPN, which is used commonly to make calculators. Commented Jun 26, 2017 at 17:39

2 Answers 2

4
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

Sign up to request clarification or add additional context in comments.

Comments

1

"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.

http://mathjs.org

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.