Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
Math operation with dynamical sign

I want to do a random math task with a random math operation sign in the middle.

The Random Numbers are fine. I do it with:

function getRandomInt(min, max) 
{
  return Math.floor(Math.random() * (max - min)) + min;
}

and save this return into var number1 and number2

Now the problem.

const mathOperationList = ['+', '-', '*', '/'];
function getRandomOperation()
{
  var randomMathOperation = mathOperationList[Math.floor(Math.random() * mathOperationList.length)];
  return randomMathOperation;
}

var mathOperation = getRandomOperation();
console.log("What is "+number1 + " "+mathOperation+" "+number2 +"?");
mathResult = number1 +mathOperation+ number2;
console.log(mathResult) 

Output is: "1+1" (not 2)

The output is a string and not a ResultInt. I know the number1+mathOperation+number2 are do it but I want a mathResult and not a String together.

How can i fix it?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use the eval function which evaluates arbitrary JavaScript code as a string.

Warning: eval is VERY dangerous due to XSS vulnerabilities and should never be used to execute non-serialized user input.

const number1 = 3, number2 = 4;

const mathOperationList = ['+', '-', '*', '/'];
function getRandomOperation()
{
  var randomMathOperation = mathOperationList[Math.floor(Math.random() * mathOperationList.length)];
  return randomMathOperation;
}

const mathOperation = getRandomOperation();
console.log("What is "+number1 + " "+mathOperation+" "+number2 +"?");
const mathResult = eval(`${number1}${mathOperation}${number2}`);
console.log(mathResult);

Using switch-case (safer)

const number1 = 3, number2 = 4;

const mathOperationList = ['+', '-', '*', '/'];
function getRandomOperation()
{
  var randomMathOperation = mathOperationList[Math.floor(Math.random() * mathOperationList.length)];
  return randomMathOperation;
}

function performOperation(left, right, operator) {
  switch (operator) {
    case "+":
      return left + right;
    case "-":
      return left - right;
    case "*":
      return left * right;
    case "/":
      return left / right;
  }
}

const mathOperation = getRandomOperation();
console.log("What is "+number1 + " "+mathOperation+" "+number2 +"?");
const mathResult = performOperation(number1, number2, mathOperation);
console.log(mathResult);

about 4 years ago · Juan Pablo Isaza Relatório

0

What not to do

You should not use eval() as it can introduces serious security issues and it is just bad practice. In your case there is not much risk as the values at the moment are not supplied by a user, but once they are you can get into serious trouble.

Let's assume you let users provide values for number and you don't check them appropriately then the following would constitute a successful Denial of Service (DoS) attack on your program because this will cause an infinite loop.

const number1 = "for(;;);";
const mathOperation = "+";
const number2 = 2;
eval(number1 + mathOperation + number2);

It also opens up other attack vectors, so just don't use eval().

What to do instead

Instead declare an array of functions, one function for every operation and randomly choose one function.

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

const mathOperationList = [
  { func: (a, b) => a + b, symbol: "+" },
  { func: (a, b) => a - b, symbol: "-" },
  { func: (a, b) => a * b, symbol: "*" },
  { func: (a, b) => a / b, symbol: "/" },
];

function getRandomOperation() {
  const randomMathOperation =
    mathOperationList[Math.floor(Math.random() * mathOperationList.length)];
  return randomMathOperation;
}

const { func: mathOperation, symbol } = getRandomOperation();
const number1 = getRandomInt(1, 10);
const number2 = getRandomInt(1, 10);
console.log("What is " + number1 + " " + symbol + " " + number2 + "?");
const mathResult = mathOperation(number1, number2);
console.log(mathResult);

about 4 years ago · Juan Pablo Isaza Relatório

0

You could take an object with all functions and get the operator first.

const
    getRandomOperator = () => operators[Math.floor(Math.random() * operators.length)],
    operators = ['+', '-', '*', '/'],
    functions = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b
    },
    operator = getRandomOperator(),
    number1 = 10,
    number2 = 5,
    result = functions[operator](number1, number2);

console.log(`What is ${number1} ${operator} ${number2}?`);
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda