Junior's code refactored solutions

There are multiple ways to refactor this code. If your solution is completely different, that’s great! JavaScript would be pretty boring if there was only one way of doing something. What is important is the general approach taken, and the main issues with the code identified.

The primary functions

I always start with identifying the primary output of the script or app. In other words, what is this code meant to do?

I can see this right at the bottom:

console.log("Package 1 shipping cost: $" + cost1);
console.log("Package 2 shipping cost: $" + cost2);
console.log("Package 3 shipping cost: $" + cost3);
console.log("Package 4 shipping cost: $" + cost4);
console.log("Package 5 shipping cost: $" + cost5);

This is the “result” or output, and it comprises two separate things:

  1. A statement to the console for each package
  2. a cost calculation

I wouldn’t want these two operations in the same function or in the same scope. They are not related. Each console.log may rely on a cost calculation, but the code for making that calculation should be kept separate.

However, I can’t see any sign of a “calculateShippingCost” function. This is my first red flag.

Repetition

It is clear there is a lot of repetition. This usually indicates two things:

  1. a lack of smaller, single-purpose functions that can be re-used.
  2. a lack of use of objects and arrays.

There is clearly repeated logic for calculating the shipping cost for each package. But even the package objects themselves have unnecessary repetition. Each is manually coded with literals, and the developer has to make sure the structure for each is matched. That is risky business!

What might we change later?

These words are ever-present in every senior’s mind. It's not only about the end result, but how code will need to be maintained.

What future changes might affect this code?

The baseCost is what caught my attention, but also the costs for the different types of shipping. If those values are embedded deeply in functions or logic, they can be difficult to extract and change later.

We also don't want to repeat the calculation logic for every package!

The solution is to use a function to calculate the cost dynamically.

Where to start

This is the code you will run at the end of the script:

const packages = // an array of package objects

// The primary calling function at the bottom of the script
// loops through each package, calculating the cost
printPackageShippingCosts(packages);

Write the functions that print the shipping cost of each package.

My solution

Have a look at this refactored solution and compare it to yours to identify the general patterns and practices. It addresses the baseCost, but not the shipping costs - what might we change so that the shipping costs are easy to change later down the line?

Links & Resources