Node.js
Listing the cart
Write the method that prints the cart formatted.
Listing the cart
To print the products in the cart we will write a printCart method. This method walks the this.items array and writes each product's name, price and quantity on one line.
You walk each product with for...of; on each iteration you print console.log(p.name + " " + p.price + " " + p.quantity);. Separating the three fields with spaces makes the output readable. The method returns no value; it only prints to the screen.
Formatted output
In printCart, while each product is written on a single line, spaces separate the fields. console.log(p.name + " " + p.price + " " + p.quantity) separates the three fields with spaces and ends with a new line.
Commas or dashes could be used instead; the formatting choice is yours. In this project we use spaces; for column alignment .padStart could fix the width. Writing three fields on one line lets you scan the cart quickly.
Exercise Write the printCart method
Add a printCart method to the Cart class. Its signature must be printCart(). In the body walk each product with for (const p of this.items) and print with console.log(p.name + " " + p.price + " " + p.quantity);. main already adds two products and calls printCart. The output must be two lines: Notebook 25 2 and Pen 10 3.
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);
}
}
}
// Test
const cart = new Cart();
cart.addItem({ name: "Notebook", price: 25, quantity: 2 });
cart.addItem({ name: "Pen", price: 10, quantity: 3 });
cart.printCart();
Test yourself
-
What does printCart do?
cart.printCart();
- Removes a product
- Computes the total
- Prints the cart to the screen
- Adds a product
Show answer
Prints the cart to the screen — printCart writes the products in the cart to the screen.
-
Write the printCart body
printCart() {
for (const p of this.items) {
console.log(____);
}
}
Show answer
printCart() {
for (const p of this.items) {
console.log(p.name + " " + p.price + " " + p.quantity);
}
}
-
Match each part to its meaning
- p.name
- Product name
- p.price
- Unit price
- p.quantity
- Quantity
- console.log
- Prints to screen
Next lesson: Putting it together