Mike
Mike

Reputation: 411

Javascript total math of string with multiple operators for js calculator

I am a student working on a javascript calculator project. I would like to take an array with multiple operators and output an answer, for example;

var equationArray = ["1", "+", "3", "/", "4", "+", "10", "*", "2"]
var answer = 22;

The current code version breaks up the array before and after the operator symbol.

if (pressedOperator === '=') {
firstpart = parseFloat(equationArray[0]);
operator = equationArray[1];
secondpart = parseFloat(equationArray[2]);
}

What would be the best way to total the array without using eval or regex?

fiddle here: https://jsfiddle.net/3daddict/8g6qrp5f/4/

Upvotes: 1

Views: 1022

Answers (1)

Unmitigated
Unmitigated

Reputation: 89314

You can join the Array on "" and then use the Function constructor to get the mathematical value of the String.

var equationArray = ["1", "+", "3", "/", "4", "+", "10", "*", "2"];
function getMathematicalValue(str){
  return new Function('return ' + str)();
}
var answer = getMathematicalValue(equationArray.join(""));
console.log(answer);

Upvotes: 2

Related Questions