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