Basic JavaScript Calculator

Chindalath Traymany
1 min readMar 25, 2021

--

Photo by Amol Tyagi on Unsplash

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?

--

--

Chindalath Traymany
Chindalath Traymany

Written by Chindalath Traymany

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

No responses yet