Final JS Exercise: Please Criticize My Code

First of all, you want to separate “global” logic from “local” logic, for instance function that deals with currencies and operations with currencies, as it “globally” applies to any “local” function that you have (or might have in future).

Additionally, if you feel that your “local” logic is a bit bulky - too many if...else for example, you normally always can break it down in few “local” functions/modules. Generally it’s healthier and easier to debug.

Regarding your approach with currencies, AND I SEE IT TOO OFTEN, you really shouldn’t expect that price * 100 will save you from precision errors. Consider this example:

const moneyInDrawer = 7;
const paid = .07;
const rest = moneyInDrawer - paid * 100;

const status = rest === 0 ? 'CLOSED' : 'OPEN'; // OPEN (Nasty bug!)

I have no idea why so many people are making this assumption, but generally, if you want to make assumption that any amount would be surely rounded to 2 decimals you would just round it to 2 decimals:

const currencify = (expression, precision = 2) => +(expression.toFixed(precision));

console.log(currencify(.2 + .1)); // 0.3
4 Likes