Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda