Create function to make calculations with a given operator using Javascript

Asked

Viewed 55 times

1

I don’t know if it would work, or if it would be the best option, but I have a code that consists of the following:

Situating that the value operacao come up with the argument +, and I want to use it to add up two values. As I should do?

Example:

function calcular(operacao){

    var num1 = 6, num2 = 2;

    var resultado = num1 + operacao + num2;
    mostrarVisor(resultado);
}

function mostrarVisor(result){

    document.getElementById('visor').innerHTML = result;    
    // aqui eu escrevo o resultado na tela!                     
}

2 answers

4

Not to use the eval, that can bring some risks, you can create a function that makes use of the switch to determine the operation.

Something like that:

function operate(x, y, op) {
  switch (op) {
    case '+':
      return x + y;
    case '-':
      return x - y;
    case '*':
      return x * y;
    case '/':
      return x / y;
    default:
      throw new Error('Invalid operator.');
  }
}

console.log(operate(4, 3, '+')); // 7
console.log(operate(6, 4, '-')); // 2
console.log(operate(3, 3, '*')); // 9
console.log(operate(8, 2, '/')); // 4

But you can still use the eval, if desired. I suggest only that you create a series of validations to ensure that no arbitrary code will be executed:

const isNumber = (val) => typeof val === 'number';

function operate(x, y, op) {
  const validOperators = ['+', '-', '*', '/'];

  if (!isNumber(x) || !isNumber(y) || !validOperators.includes(op)) {
    throw new Error('Invalid arguments.');
  }

  return eval(`${x} ${op} ${y}`);
}

console.log(operate(4, 3, '+')); // 7
console.log(operate(6, 4, '-')); // 2
console.log(operate(3, 3, '*')); // 9
console.log(operate(8, 2, '/')); // 4

0

Amgio, I believe what you’re looking for is the method eval(), it takes a string, and if it is an expression Eval will calculate the result:

eval("1 + 1");

The output of the above command will be 2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.