Problem
- Given two numbers and an arithmetic operator, return the result of the two numbers having that operator used on them.
- 두 개의 숫자와 산술 연산자가 주어진다.
- 연산자가 사용된 두 숫자의 결과를 반환한다.
Solution 01
function arithmetic(a, b, operator) {
if (operator === 'add') return a + b;
if (operator === 'subtract') return a - b;
if (operator === 'multiply') return a * b;
if (operator === 'divide') return a / b;
}
arithmetic(2, 4, 'add'); // 6
arithmetic(4, 2, 'subtract'); // 2
arithmetic(4, 4, 'multiply'); // 16
arithmetic(8, 4, 'divide'); // 2
Solution 02
function arithmetic(a, b, operator) {
switch (operator) {
case 'add':
return a + b;
case 'subtract':
return a - b;
case 'multiply':
return a * b;
case 'divide':
return a / b;
}
}
arithmetic(2, 4, 'add'); // 6
arithmetic(4, 2, 'subtract'); // 2
arithmetic(4, 4, 'multiply'); // 16
arithmetic(8, 4, 'divide'); // 2
Solution 03
function arithmetic(a, b, operator) {
const obj = {
add: a + b,
subtract: a - b,
multiply: a * b,
divide: a / b
};
return obj[operator];
}
arithmetic(2, 4, 'add'); // 6
arithmetic(4, 2, 'subtract'); // 2
arithmetic(4, 4, 'multiply'); // 16
arithmetic(8, 4, 'divide'); // 2