I am fairly novice when it comes to programming and javascript in general, and I'm running through some example questions to get better over at CodeWars.com
The question I just completed asks the following:
Write a function called calculate that takes 3 values. The first and third values are numbers. The second value is a character. If the character is "+" , "-", "*", or "/", the function will return the result of the corresponding mathematical function on the two numbers. If the string is not one of the specified characters, the function should return null.
It gives you this following code to start out with:
function calculate(num1, operation, num2) {
//TODO: make a basic calculator.
It checks your code against the following test cases:
Test.assertSimilar(calculate(3.2,"+", 8), 11.2, "3.2 + 8 = 11.2")
Test.assertSimilar(calculate(3.2,"-", 8), -4.8, "3.2 - 8 = -4.8")
Test.assertSimilar(calculate(3.2,"/", 8), 0.4, "3.2 / 8 = .4")
Test.assertSimilar(calculate(3.2,"*", 8), 25.6, "3.2 * 8 = 25.6")
Test.assertSimilar(calculate(-3,"+", 0), -3, "-3 + 0 = -3")
Test.assertSimilar(calculate(-3,"-", 0), -3, "-3 - 0 = -3")
Test.assertSimilar(calculate(-3,"/", 0), null, "-3 / 0 = null")
Test.assertSimilar(calculate(-3,"*", 0), 0, "-3 * 0 = 0")
Test.assertSimilar(calculate(-3,"w", 0), null, "-3 w 0 = null")
I completed all of the test cases by running through a series of if and else if loops ( JSFiddle ):
function calculate(num1, operation, num2) {
//TODO: make a basic calculator.
if (operation === '+'){
console.log(num1 + num2);
}
else if (operation === '-'){
console.log(num1 - num2);
}
else if (operation === '/'){
console.log(num1 / num2);
}
else if (operation === '*'){
console.log(num1 * num2);
}
else{
return null;
}
}
calculate(3.2,"*", 8);
calculate(-3,"+", 0);
calculate(-3,"-", 0);
I know this isn't the most elegant solution, and I would love to find ways to improve and simplify the code. The hardest part about starting something new is being able to ask the right questions, so I would love if I could get some input on how to better simplify my code!
Thanks