Error with Tip 2 Final Code (const.js)
Closed this issue · 3 comments
"The final code..." in Tip 2, simplifying-js/variables/let/const.js still has a bug.
Using the item object where inventory equals zero, but saleInventory has a count greater than zero, the function will return zero instead of the price. It's because the saleCount is used to determine price (salePrice), but never used to determine if price should be returned.
`const item ={ inventory:0, price:3, saleInventory:1, salePrice:5 };
function getLowestPrice(item) {
const count = item.inventory;
let price = item.price;
if (item.salePrice) {
const saleCount = item.saleInventory;
if (saleCount > 0) {
price = item.salePrice;
}
}
if (count) {
return price;
}
return 0;
}
console.log(getLowestPrice(item)); // Should display 5 instead of 0
`
That's not a bug. We should never return a price if the inventory is 0. That means there are none to sell. If the sale Inventory has a count, but the regular inventory does not have a count, we should trust the regular inventory.
You are correct that if we wanted to trust either inventory, we would just return the price if saleCount > 0.
Meh, sorry Joe! :)
Reading back through it, I actually saw the bullet where you specifically pointed out Return 0 if no inventory.
I realize these are sometimes slightly contrived examples to get across a point. When I say contrived here, I mean code style - I know you also mentioned at the beginning of the book that you wanted to try and use real world examples, and I think this fits a real world situation fine.
I think where I got confused is when the code would still set the sale price even if no inventory, so it would seem like you would want to show that if you're taking the time to set it.
Below is a cleaner way to show intent, and also not process any unnecessary logic. However, this cleaner approach passes the double var declaration using saleInventory = 0, which wouldn't help illustrate the point you were trying to make, hence having to create a somewhat contrived example.
`const item = {
inventory: 3,
price: 3,
salePrice: 2,
saleInventory: 0
};
function getLowestPrice(item) {
var count = item.inventory;
var price = 0;
if (count) {
var count = item.saleInventory;
if (count && item.salePrice) {
price = item.salePrice;
} else {
price = item.price;
}
}
return price;
}
console.log(getLowestPrice(item)); // Correctly outputs 3`
Again, sorry for opening up a non issue. Wish I would've paid attention to the bullet points!
No problem. I would definitely prefer your code in production!
I think I could've come up with a better example here, but I'm stuck with this one now :)