CodeBlanks Logo Icon CodeBlanks

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ı.

Başlangıç kodu

index.js
class Cart {
    constructor() {
        this.items = [];
    }
    addItem(product) {
        this.items.push(product);
    }
}
    // getSubtotal metodunu buraya yaz
}

// 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());

Örnek çözüm

index.js
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());

Beklenen çıktı

80

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 getSubtotal gövdesini yaz

Soru
let sum = 0;
for (const p of this.items) {
    ____;
}
return sum;
Cevap
let sum = 0;
for (const p of this.items) {
    sum += p.price * p.quantity;
}
return sum;

Açıklama: Her ürünün katkısı price * quantity'dir.

2 Kavramı anlamına eşle

Kavram Anlamı
Subtotal Vergi hariç toplam
Tax Vergi oranı
Total Vergi dahil toplam
Quantity Ürün adedi

3 Bir ürünün sepetteki katkısı nedir?

index.js
// sepette p ürünü
  • p.name
  • p.price * p.quantity Doğru cevap
  • p.price + p.quantity
  • p.quantity

Açıklama: Birim fiyat çarpı miktar: p.price * p.quantity.

Başlangıç bölümündeki tüm dersler