Node.js
Toplam hesaplama
Subtotal ve vergi dahil toplamı hesaplamayı öğrenirsin.
Toplam hesaplama
Sepetteki ürünlerin ara toplamını hesaplamak için getSubtotal metodunu yazacağız. Her ürünün katkısı p.price * p.quantity'dir; tüm ürünleri gezip toplayarak ara toplamı buluruz.
Bu, klasik bir birikim (accumulation) örneğidir: let sum = 0; ile başla, for...of ile her ürünü gez, sum += p.price * p.quantity ile topla. Son olarak return sum; ile sonucu döndür. Birikim kalıbı, stok sayımı, ortalama ve benzeri birçok hesapta işine yarayacak.
Subtotal ve total farkı
Subtotal, vergi ve ek ücretler hariç ara toplamdır. Vergi dahil toplamı bulmak için subtotal * (1 + taxRate) kullanılır; örneğin %18 vergi için 1.18 çarpanı alınır.
Bu projede getSubtotal yalnızca ara toplamı döndürür; vergili toplamı main içinde hesaplayabilirsin. İki kavramı ayırmak, vergi oranı değiştiğinde sadece çarpanı güncellemeyi kolaylaştırır. Ülkeden ülkeye değişen vergi oranları için bu ayrım önemlidir.
Uygulama getSubtotal metodunu yaz
Cart sınıfına bir getSubtotal metodu ekle. İmzası getSubtotal() olmalı. Gövdede let sum = 0; ile başla, for (const p of this.items) ile her ürünü gez, sum += p.price * p.quantity ile topla ve return sum; ile döndür. main iki ürün ekleyip getSubtotal'ı yazdırıyor. Çıktı tek satırda 80 olmalı.
Örnek çözümü göster
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;
}
}
// Test
const cart = new Cart();
cart.addItem({ name: "Defter", price: 25, quantity: 2 });
cart.addItem({ name: "Kalem", price: 10, quantity: 3 });
console.log(cart.getSubtotal());
Kendini test et
-
getSubtotal gövdesini yaz
let sum = 0;
for (const p of this.items) {
____;
}
return sum;
Cevabı göster
let sum = 0;
for (const p of this.items) {
sum += p.price * p.quantity;
}
return sum;
-
Kavramı anlamına eşle
- Subtotal
- Vergi hariç toplam
- Tax
- Vergi oranı
- Total
- Vergi dahil toplam
- Quantity
- Ürün adedi
-
Bir ürünün sepetteki katkısı nedir?
// sepette p ürünü
- p.name
- p.price * p.quantity
- p.price + p.quantity
- p.quantity
Cevabı göster
p.price * p.quantity — Birim fiyat çarpı miktar: p.price * p.quantity.
Sıradaki ders: Sepeti listeleme