Basic JavaScript Calculator
This week, I thought I’d challenge myself to implement a simple calculator. I started off with a string input consisting of two numbers and the basic operations (+, -, *, /).
I immediately thought, I could proceed with a switch
statement, and came up with my function.
function calculator(string) { let calculation = string.split(/\b\s*([+\/*-])\s*/) const expression = calculation[1] switch(expression) { case "*": return parseInt(calculation[0])*parseInt(calculation[2]) break; case "/": return parseInt(calculation[0])/parseInt(calculation[2]) break; case "+": return parseInt(calculation[0])+parseInt(calculation[2]) break; case "-": return parseInt(calculation[0])-parseInt(calculation[2]) break; default: return (`Error ${string} contains an invalid operation.`) }}
Voila! Functional.
I wanted to shift focus to the second line of the code, which was provided through Stack Overflow.
let calculation = string.split(/\b\s*([+\/*-])\s*/)
When I first tried splitting by operation, I quickly saw several edge cases that were not being covered. Thankfully, I came across the code above with a quick Google search. This line uses Regular Expression to elegantly split
the string input, ignoring periods, and including negatives in order to get an accurate and hassle-free result.
Now that we have the basic calculator down, how would you support the order of operations in a more advanced calculator?