Latihan 1: Refactoring Techniques — Clean Code

Latihan 1 dari materi Refactoring Techniques di Clean Code — praktek dengan editor kode interaktif, test case otomatis, dan hint terpandu. Langsung jalan di browser.

getDiscount(type, price) di editor memilih diskon dengan rantai if/else if. Refactor dengan teknik Replace Conditional with Lookup:

  1. Buat object DISCOUNT_RATES yang memetakan tipe ke tarif diskon: regular: 0, member: 0.1, vip: 0.2, employee: 0.3.
  2. Tulis ulang getDiscount(type, price): ambil tarifnya dari DISCOUNT_RATES[type], pakai 0 kalau tipenya gak ada di tabel (?? 0 atau || 0), lalu kembalikan price * (1 - rate).
  3. Gak boleh ada else if lagi di kode.

Lima console.log di bawah tetap ada. Output-nya harus:

100000
90000
80000
70000
100000

getDiscount juga diuji sendiri: getDiscount('vip', 100000) harus 80000, getDiscount('tidak-ada', 100000) harus 100000, dan DISCOUNT_RATES.employee harus 0.3.

Hint