Refactoring a Javascript Calculator

Refactoring a simple calculator web app

The Why

Before I started Fullstack Academy, I had gone through most of the Free Code Camp front end curriculum. One thing that I found I was missing is a general best practices. It never occurred to me that a calculator could be an object with methods even though I knew how to create objects with method. Free Code Camp gives you some basic tools, but doesn’t tell you if you’re making something smart or just making it hacky.

Anyway, I’ve decided to refactor the JS, JQuery calculator web app I made for Free Code Camp using a calculator object. If time allows, I will refactor it again as a parser, because… why not?

The original code pen of the original version can be found here: Simple Javascript Calculator

The calculator object

In my original version, on each operation, I was putting the total, operator, and new input into a string and evaluating. I had the text field set up so you could only input by button to prevent errors, so this also would have prevented any hacking being done through the input. But honestly, I didn’t even know at the time that a hacker could enter code in a text input that is then passed into an eval statement.

In the object version I created a calculator object with a total, a next, and methods to add, subtract, multiply, and divide. Other functionality that was in my original calculator include clear all, clear entry, backspace, and +/-.

Clearing the calculator

Using the object method seems have simplified clearing the calculator, I can just make a new calculator.

Adding functionality

Each operation button will need to grab the current input value, run the last operation, clear the next value and save the current operation.

1
2
3
4
5
6
7
8
9
10
$('#plus').click(function(){
if(calc.lastOperation){
calc.lastOperation(+calc.next);
}else{
calc.setTotal(+calc.next);
}
$('#numberIn').val(calc.getTotal());
calc.next = "";
calc.lastOperation = calc.add;
})

I then created a runLast function to complete the first 6 lines in the plus click function and used that for minus, divide, multiply, and equals.
All the basic functionality of a calculator is now there.

Next Steps

-I attempted to add the click functions to the number button with a loop but it wasn’t working. I could figure this out.
-I could wrap the entire javascript, not just the calculator, inside an object. This would be a good exercise in ‘this’, binding, and arrow functions.
-When you click the equals button it stops the chaining and you have to start over. This is a little buggy as you may want to do an operation on your result.

-Rewrite the calculator as a parser that can handle parentheses.