DEV Community

Alex Morton
Alex Morton

Posted on

Refactoring My Tip Calculator Program

In one of my exercises from my JS course yesterday, we had to create an object, john, representing a person and the number and prices of meals he had on vacation and how much he tipped with each meal. According to instructions, he preferred to tip as follows:

  • For meals less than $50, tip 20%
  • For meals between $50 and $200, tip 15%
  • For meals over $200, tip 10% (I know - I wouldn't want to be John's server either.)

Here's the code I started off with for calculating both the individual tips he gave for each meal, as well as each total meal cost (cost of meal with tip included):

```          
  var john = {
    bills: [124, 48, 268, 180, 42],
    tips: [],
    totalMealCosts: [],
    calcTip: function(){
      var tip;
      var totalMealCost;

      for (let i = 0; i < this.bills.length; i++) {
        var bill = this.bills[i];
        if (bill > 0 && bill < 50) {
          tip = bill * 0.2;
          totalMealCost = bill + tip;
        } else if (bill >= 50 && bill <= 200) {
          tip = bill * 0.15;
          totalMealCost = bill + tip;
        } else {
          tip = bill * 0.1;
          totalMealCost = bill + tip;
        } 
      this.tips.push(tip);
      this.totalMealCosts.push(totalMealCost);
      } 
    }
  };
 ```
Enter fullscreen mode Exit fullscreen mode

And then after some refactoring, this is my final program (manually transpiled from ES5 to ES6):

```       
  const john = {
    bills: [124, 48, 268, 180, 42],
    tips: [],
    totalMealCosts: [],
    calcTip: function(){
      let totalMealCost;
      let tipAmount;
      for (let i = 0; i < this.bills.length; i++) {
        let bill = this.bills[i];
        let percentage;
         if (bill < 50) {
          percentage = 0.2;
        } else if (bill >= 50 && bill <= 200) {
          percentage = 0.15;
        } else {
          percentage = 0.1;
        } 

      tipAmount = bill * percentage;
      totalMealCost = bill + tipAmount;

      this.tips.push(tipAmount);
      this.totalMealCosts.push(totalMealCost);
       } 
     }
   };
```
Enter fullscreen mode Exit fullscreen mode

The main thing here is the fact that I removed the tipAmount and totalMealCost variables from each tipping condition and moved them instead to the end of the for loop.

I'm working more on not repeating myself in my code, and I'm realizing that it all comes down to practicing and eventually reaching higher skill levels - after a certain amount of time, thinking about how your own code could be improved becomes as natural as anything.

This post was originally published on February 5, 2020 on my blog

Top comments (0)