Challenge: Solution Review
This lesson will explain the solution to the problem from the previous coding challenge.
We'll cover the following...
Solution #
class Inventory{constructor(){this.shampoosAmount = 20this.conditionersAmount = 20this.hairSerumsAmount = 1000}checkInventory(product){let available = true;if(product.productName == "shampoo" && product.amount > this.shampoosAmount){available = falsereturn available}else if(product.productName == "conditioner" && product.amount > this.conditionersAmount){available = falsereturn available}else if(product.productName == "hair serum" && product.amount > this.hairSerumsAmount){available = falsereturn available}return available}}class BuyingProduct extends Inventory {buyProduct(product) {let order;if(this.checkInventory(product)){order = new BuyProduct()}else{order = new PreOrderProduct()}return order.showDetails(product)}}class BuyProduct{showDetails(product){console.log(`${product.amount} bottles of ${product.productName} are available. Click on "buy" to purchase them.`)}}class PreOrderProduct{showDetails(product){console.log(`${product.amount} bottles of ${product.productName} are not available. You can Pre-order them on the next page.`)}}var customer = new BuyingProduct()customer.buyProduct({productName: "shampoo", amount: 2})customer.buyProduct({productName: "hair serum", amount: 2000})
Explanation
Before we delve into the solution, let’s summarize what the challenge is. Here, you have to provide a simple ordering interface for the customer. The implementation should be such that when a customer wants to buy a product, they get a message that says the product is available for purchase or pre-order . You have to use the facade pattern here to hide all the background processing that the customer doesn’t need to see.
Now, let’s discuss what goes on behind the scenes. We need to implement the following when a purchase request is made:
-
check whether the product is available or not
-
if available, display a message conveying its availability to the customer
-
if it is not available, display a corresponding message
To check whether a product is available or not, we defined the Inventory
...