Search code examples
javascriptarraysstringeval

Evaluate maths operators from string to use with random number


I have a maths quiz, where the numbers are randomized and so are the operators but to make the operators random I had to put them in a string and use Math.random which all works however when trying to calculate the questions I am unsure how to evaluate the maths operators.

var operationArray = ['x','&#247','+','-'];
var randomOperation1 = Math.floor(Math.random()*operationArray.length);
var randomOperation2 = Math.floor(Math.random()*operationArray.length);


  var randomNumber1 = Math.floor(Math.random() * 6) + 5;
  var randomNumber2 = Math.floor(Math.random() * 8) + 10;
  var randomNumber3 = Math.floor(Math.random() * 40 + 1);
  _questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;

_decimalAnswer = randomNumber1 + randomNumber2 + randomNumber3;
  _answer = Math.round(_decimalAnswer);

After researching I came across eval() but failed to see how this would work when the numbers have random values and the operators are strings.


Solution

  • Allthough i would not recommend using eval ( evil ) at all. This might be necessary in this case.

    var operationArray = ['x','&#247','+','-'];
    var randomOperation1 = Math.floor(Math.random()*operationArray.length);
    var randomOperation2 = Math.floor(Math.random()*operationArray.length);
    
    var randomNumber1 = Math.floor(Math.random() * 6) + 5;
    var randomNumber2 = Math.floor(Math.random() * 8) + 10;
    var randomNumber3 = Math.floor(Math.random() * 40 + 1);
    _questionText = document.getElementById("question").innerHTML = randomNumber1 + " " + operationArray[randomOperation1] + " " + randomNumber2 + " " + operationArray[randomOperation2] + " " + randomNumber3;
    

    Replace the operators with the actual operators used by the code

    _questionText = _questionText.replace(/&#247/g, '/').replace(/x/g, '*');
    

    Evaluate the string.

    _decimalAnswer = eval(_questionText);
    _answer = Math.round(_decimalAnswer);