JS calculator issue. Wrong Answer

I'm writing a one-line calculator, that has the basic functions (+ - * /). I have done this before, but now I keep getting wrong answers, and I can't find my mistake. Here is my code:

var seq = document.getElementById('sequence').value;
var allNums = [];
var i = 0, allSigns = [];
var currentNums = "";

for (i = 0; i< seq.length; i++)
{
    if (seq[i] != "+" && seq[i] != "-" && seq[i] != "*" && seq[i] != "/")
    {
        currentNums+=seq[i];
    }
    else
    {
        allNums.push(Number(currentNums));
        currentNums="";
        allSigns.push(seq[i]);
    }
}
allNums.push(Number(currentNums));
var result = 0;
for (i = 0; i < allNums.length; i++)
{
    if (allSigns[i] == '+')
        result+=Number(allNums[i]);
    else if (allSigns[i] == "-")
        result-=Number(allNums[i]);
    else if (allSigns[i] == "*")
        result*=Number(allNums[i]);
    else if (allSigns[i] == "/")
        result/=parseInt(allNums[i]);
    else
    {
        alert("The result is: " + result);
        break;
    }
}

All of this code is in a function, called calculate. The func is triggered by a button, and the sequence comes from an input.


Solution 1:

Though there are numerous shortcomings with this simple calculator that may or may not be a problem (depending on what you want to do with it), one issue is that your allSigns array values aren't being associated with the correct allNums array values.

Take a look at this example. In the console, you can see that the sign associated with the 6 is the plus sign, while the operator associated with 2 is undefined. This isn't what we want, of course. What we want is to add the two to the six.

The fix for this issue would be always adding allNums[0] to the result from the start. This sets up our result to be operated upon by anything following it. In this case, we start off with 6.

Next what we need to do is shift the position of each value of allSigns down by one, lining up the operator with the value after it, and not before it. So, in the example above, we'd have + associated with 2, so it'd add the two to the six.

This JSFiddle shows the fix for this specific case.