TypeScript
Integration
Build the working cart by combining all parts.
Combine all parts
The cart project has three main functions: addToCart (add product), total (compute total), applyDiscount (apply discount). When using a cart, you first add products, then compute the total, and finally apply a discount.
function addToCart(cart: Cart, product: Product, quantity: number): Cart { /* ... */ }
function total(cart: Cart): number { /* ... */ }
function applyDiscount(amount: number, percent: number): number { /* ... */ }
Working example
If you add apple (price 5, quantity 2) and milk (price 10, quantity 1) to a cart, the total is 20. With a 10% discount, the final price is 18.
const apple: Product = { id: "a", name: "Elma", price: 5 };
const milk: Product = { id: "b", name: "Süt", price: 10 };
const cart: Cart = { items: [] };
addToCart(cart, apple, 2);
addToCart(cart, milk, 1);
const t = total(cart);
const final = applyDiscount(t, 10);
console.log(final); // 18
Exercise Write the working cart
Define Product, CartItem, Cart interfaces. Write addToCart, total, applyDiscount functions. Add apple (id: "a", price 5) and milk (id: "b", price 10) to the cart (2 apples, 1 milk). Compute the total, apply a 10% discount, and print the final price.
Show example solution
interface Product { id: string; name: string; price: number; }
interface CartItem { product: Product; quantity: number; }
interface Cart { items: CartItem[]; }
function addToCart(cart: Cart, product: Product, quantity: number): Cart {
const existing = cart.items.find(i => i.product.id === product.id);
if (existing) {
existing.quantity += quantity;
return cart;
}
cart.items.push({ product, quantity });
return cart;
}
function total(cart: Cart): number {
return cart.items.reduce((sum, i) => sum + i.product.price * i.quantity, 0);
}
function applyDiscount(amount: number, percent: number): number {
return amount * (1 - percent / 100);
}
const apple: Product = { id: "a", name: "Elma", price: 5 };
const milk: Product = { id: "b", name: "Süt", price: 10 };
const cart: Cart = { items: [] };
addToCart(cart, apple, 2);
addToCart(cart, milk, 1);
const cartTotal = total(cart);
const finalPrice = applyDiscount(cartTotal, 10);
console.log(finalPrice);
Test yourself
-
In which order is a cart's final price computed?
- First add, then total, then discount
- First discount, then add, then total
- First total, then add, then discount
- First add, then discount, then total
Show answer
First add, then total, then discount — You add products to the cart, then compute the total of all items, and finally apply a discount to get the final price.
-
Complete the final step
const finalPrice = ____(cartTotal, 10);
Show answer
const finalPrice = applyDiscount(cartTotal, 10);
-
Integration flow
- addToCart
- First step: add
- total
- Second step: total
- applyDiscount
- Third step: discount
- finalPrice
- Result
Next lesson: Task model