# Javascript Calculator & Order of Operations

How do I tackle Mathematical Order of Operations from user inputs in the JS Calculator Challenge?

3+1x3 = 6; NOT 12

The example calculator, given to us, does not function correctly and I’m at a loss as to where to find solutions to this …

any help would be much appreciated, it’s driving me crazy …

You gonna have to do it the hard way. Parse the string to find all the operator and the associate operand. Then put them in order to perform the calculation.

Do small pieces at a time. Like find the operator.
Then the operand.

1 Like

that’s what I was afraid of … it came to me after I posted the question … gonna be an arduous task … but SO WORTH IT … thanks

Here is an example I just wrote. Seems to work but I didnt tested it for every combination.

//STR TO INT FROM UI
var digits = “”;

//THE OP + NUMS (from digits)
var math = [];

//THE RESULT
var res = 0;

//SCREEN
var view;
view = document.getElementById(‘view’);

//CREATE A NUMBER FROM DIGITS[str]
function getValue(val) {
digits += val;
}

//TAKES CARE OF THE CHRONOLOGY and RETURNS THE RESULT
function opChrono(arr, id) {
//LAST NUMBER EXCEPTION
if (digits) {
math.push(parseFloat(digits));
digits = “”;
}
arr.map(function(val, idx, arr) {
//MULTI FIRST
if (val == “") {
arr.splice((idx - 1), 3, (arr[idx - 1] * arr[idx + 1]));
}
//THEN DIVISION
if (arr.indexOf("
”) == -1 && val == “/”) {
arr.splice((idx - 1), 3, (arr[idx - 1] / arr[idx + 1]));
}
})

``````//no MULTI/DIV
if (arr.indexOf("*") == -1 && arr.indexOf("/") == -1) {

//FIRST NUMBER EXCEPTION
res += arr[0];

//GEN RES
arr.map(function(value, index, arr) {
if (value == "-" || value == "+") {
res += parseFloat(value + arr[index + 1]);
}
})

//SHOW RES
view.innerHTML = res;
//RECU STOP
return arr;
};
//RECU GO
return opChrono(arr, id);
``````

}

function getSign(id) {
//create INT and put into OP ARR
math.push(parseFloat(digits));
//the SIGN
lastSign = document.getElementById(id).id;
if (lastSign != “eq”) {
math.push(lastSign);
}
//show
view.innerHTML = math.join(" ");
//reset to create a new NUMBER
digits = “”;
}