Task is basically:
"Write a function which takes two number as the first two parameter. The third parameter is one of the arithmetic operators (+ , - , * , /). Execute the arithmetic operation (number1 operator number2) and return the result of it."
Here's the first idea I've had:
function calculate(num1, num2, operator) {
num1 = parseFloat(num1);
if (isNaN(num1)) {
throw Error('First parameter invalid. Must be a number.');
}
num2 = parseFloat(num2);
if (isNaN(num2)) {
throw Error('Second parameter invalid. Must be a number.');
}
operator = operator.trim();
if (!/^\+$|^\-$|^\*$|^\/$/.test(operator)) {
throw Error('Third parameter invalid. Valid are + | - | * | /');
}
return eval(num1 + operator + num2);
}
Then I've had another idea for the implementation which uses the ES6-syntax:
function calculate2(num1, num2, operator) {
num1 = parseFloat(num1);
if (isNaN(num1)) {
throw Error('First parameter invalid. Must be a number.');
}
num2 = parseFloat(num2);
if (isNaN(num2)) {
throw Error('Second parameter invalid. Must be a number.');
}
operator = operator.trim();
if (!/^\+$|^\-$|^\*$|^\/$/.test(operator)) {
throw Error('Third parameter invalid. Valid are + | - | * | /');
}
var calculations = {
'+' : (numb1, numb2) => numb1 + numb2,
'-' : (numb1, numb2) => numb1 - numb2,
'*' : (numb1, numb2) => numb1 * numb2,
'/' : (numb1, numb2) => numb1 / numb2
}
return calculations[operator](num1, num2);
}
I still like the eval-version a bit better.
Can't see any harm which eval should create here because it's controlled via regular expression what is passed until that point.
What's your opinion?
Which implementation is better one?
Looking forward reading your answers.
Array.prototype.includes
-- looks nicer, is part of ES2016, but may need to be polyfilled. \$\endgroup\$/^[-+*/]$/
\$\endgroup\$