문제

  • 사칙연산을 수행하는 함수를 작성한다.

풀이 01

function basicMathOp(operation, value1, value2) {
  if (operation === '+') return value1 + value2;
  if (operation === '-') return value1 - value2;
  if (operation === '*') return value1 * value2;
  if (operation === '/') return value1 / value2;
}

basicMathOp('+', 1, 2);  // 3
basicMathOp('-', 4, 2);  // 2
basicMathOp('*', 4, 4);  // 16
basicMathOp('/', 8, 2);  // 4

풀이 02

function basicMathOp(operation, value1, value2) {
  switch (operation) {
    case '+': return value1 + value2;
    case '-': return value1 - value2;
    case '*': return value1 * value2;
    case '/': return value1 / value2;
  }
}

basicMathOp('+', 1, 2);  // 3
basicMathOp('-', 4, 2);  // 2
basicMathOp('*', 4, 4);  // 16
basicMathOp('/', 8, 2);  // 4

풀이 03

function basicMathOp(operation, value1, value2) {
  const obj = {
    '+': value1 + value2,
    '-': value1 - value2,
    '*': value1 * value2,
    '/': value1 / value2
  };

  return obj[operation];
}

basicMathOp('+', 1, 2);  // 3
basicMathOp('-', 4, 2);  // 2
basicMathOp('*', 4, 4);  // 16
basicMathOp('/', 8, 2);  // 4