Node.js
Putting it together
Combine the cart class with a CLI.
Putting it together
All pieces are ready: the Cart class, the addItem, getSubtotal and printCart methods. Now we will combine them in the main flow to create two products in the cart, print the cart and show the total.
At this stage each method does its own job; main just calls them in order. A well-designed program scales by keeping methods small and focused. If you want to add a new feature to the cart later, you only need to change the relevant method.
End-to-end flow
When all parts of the cart application come together you get a real shopping flow: products are added, the cart is shown and the total is computed. Each method does one job well.
Later you can wrap this in a menu loop to offer choices to the user. The pattern while (choice !== 0) shows the menu again until 0 is entered. For now we will drive the flow with direct calls; you will see interactive menus in later projects.
Exercise Integrate the cart
All methods of the Cart class are ready. In the main flow write these steps: first create the cart with const cart = new Cart(); then add two products with cart.addItem({ name: "Notebook", price: 25, quantity: 2 }) and cart.addItem({ name: "Pen", price: 10, quantity: 3 }); then print the cart with cart.printCart(); finally print the total with console.log("Total: " + cart.getSubtotal()). The output must be three lines: Notebook 25 2, Pen 10 3, Total: 80.
Show example solution
class Cart {
constructor() {
this.items = [];
}
addItem(product) {
this.items.push(product);
}
getSubtotal() {
let sum = 0;
for (const p of this.items) {
sum += p.price * p.quantity;
}
return sum;
}
printCart() {
for (const p of this.items) {
console.log(p.name + " " + p.price + " " + p.quantity);
}
}
}
const cart = new Cart();
cart.addItem({ name: "Notebook", price: 25, quantity: 2 });
cart.addItem({ name: "Pen", price: 10, quantity: 3 });
cart.printCart();
console.log("Total: " + cart.getSubtotal());
Test yourself
-
Write the main integration line
cart.printCart();
console.log("Total: " + ____);
Show answer
cart.printCart();
console.log("Total: " + cart.getSubtotal());
-
Match each piece to its job
- Cart
- Holds all the data
- addItem
- Adds to the cart
- printCart
- Shows the cart
- getSubtotal
- Returns the total
-
Which construct calls all pieces in the integration step?
// integrated flow
Show answer
main flow — The main flow calls all methods in order.
Next lesson: Declaring arrays