basicMathOp.js (8kyu 10)

Codewars 알고리즘 풀이


Problem

  • Your task is to create a function that does four basic mathematical operations.
    • 사칙 연산을 수행하는 함수를 작성한다.


Solution 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


Solution 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


Solution 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