File size: 1,675 Bytes
63f6453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
 * Alışveriş sepeti. Fiyatlar kuruş (tam sayı) olarak tutulur.
 */
class Cart {
  constructor() {
    this.items = new Map(); // sku -> { name, unitPrice, qty }
    this.coupon = null;
  }

  add(sku, name, unitPrice, qty = 1) {
    if (!Number.isInteger(unitPrice) || unitPrice < 0) throw new TypeError('unitPrice negatif olmayan tam sayı olmalı');
    if (!Number.isInteger(qty) || qty < 1) throw new RangeError('qty en az 1 olmalı');
    const cur = this.items.get(sku);
    if (cur) cur.qty += qty;
    else this.items.set(sku, { name, unitPrice, qty });
    return this;
  }

  remove(sku, qty = Infinity) {
    const cur = this.items.get(sku);
    if (!cur) return false;
    if (qty >= cur.qty) this.items.delete(sku);
    else cur.qty -= qty;
    return true;
  }

  subtotal() {
    let sum = 0;
    for (const { unitPrice, qty } of this.items.values()) sum += unitPrice * qty;
    return sum;
  }

  applyCoupon(code) {
    const coupons = { YUZDE10: { type: 'percent', value: 10 }, INDIRIM50: { type: 'fixed', value: 5000 } };
    const c = coupons[String(code).toUpperCase()];
    if (!c) throw new Error('Geçersiz kupon');
    this.coupon = c;
  }

  discount() {
    const sub = this.subtotal();
    if (!this.coupon) return 0;
    if (this.coupon.type === 'percent') return Math.round((sub * this.coupon.value) / 100);
    return Math.min(this.coupon.value, sub);
  }

  shipping() {
    const afterDiscount = this.subtotal() - this.discount();
    if (this.items.size === 0) return 0;
    return afterDiscount >= 50000 ? 0 : 2999;
  }

  total() {
    return this.subtotal() - this.discount() + this.shipping();
  }
}

module.exports = { Cart };