Switch case calculator in JavaScript


Let’s say, we are required to write a JavaScript function that takes in a string like these to create a calculator −

"4 add 6"
"6 divide 7"
"23 modulo 8"

Basically, the idea is that the string will contain two numbers on either sides and a string representing the operation in the middle.

The string in the middle can take one of these five values −

"add", "divide", "multiply", "modulo", "subtract"

Our job is to return the correct result based on the string

Example

Let’s write the code for this function −

const problem = "3 add 16";
const calculate = opr => {
   const [num1, operation, num2] = opr.split(" ");
   switch (operation) {
      case "add":
         return +num1 + +num2;
      case "divide":
         return +num1 / +num2;
      case "subtract":
         return +num1 - +num2;
      case "multiply":
         return +num1 * +num2;
      case "modulo":
         return +num1 % +num2;
      default:
         return 0;
   }
}
console.log(calculate(problem));

Output

The output in the console: −

19

Updated on: 15-Sep-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements