0

Just starting learn js, how can I get results like what shows in the examples.

So the require is like this:

Create a function that takes two numbers and a mathematical operator + - / * and will perform a calculation with the given numbers.

Examples

calculator(2, "+", 2) ➞ 4

calculator(2, "*", 2) ➞ 4

calculator(4, "/", 2) ➞ 2

Notes

If the input tries to divide by 0, return: "Can't divide by 0!"

function calculator (a, b) {
  let output = 0;
  output = a+b;
  return output;
}
console.log(calculator(2,2));

Here is what I wrote, only for performing "+".

I thought maybe I should try to add another parameter to repersent "+*/", but I can't get it right.

Anyone can help with it? Thanks

Gao
  • 11
  • 1
  • 1
  • You could even try to implement a function taking three parameters ... – Teemu May 05 '21 at 07:06
  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+function+that+takes+two+numbers+and+operator) of [Javascript function - converting string argument to operator](https://stackoverflow.com/q/52086419/4642212). – Sebastian Simon May 05 '21 at 07:41

2 Answers2

3

This should work

function calculator (a, b, c) {
  let output = 0;

  try {

    switch(c) {
      case '+':
        output = a + b
        break;

      case '*':
        output = a * b
        break;

      case '-':
        output = a - b
        break;

     case '/': 
        if (b === 0) {
          throw "Can't divide by 0!"
        } else {
          output = a / b
        }
        break;
    }
  }
  catch(e) {
    console.log("There's an error: ", e)
  }

  return output;
}

console.log(calculator(2,2,'*'));
the_previ
  • 683
  • 6
  • 12
0

Here is the function:

const calculator = (a, b, operation) => {
  if (operation === '+') return a + b;
  if (operation === '-') return a - b;
  if (operation === '*') return a * b;
  if (operation === '/') return b === 0 ? "Can't divide by 0!" : a / b;
}

console.log(calculator(10, 10, "*"));
NeNaD
  • 18,172
  • 8
  • 47
  • 89