Skip to content

Instantly share code, notes, and snippets.

@mcsee
Last active August 21, 2023 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcsee/2f7aee362e99fbe447d8c1e8aaeb9f8e to your computer and use it in GitHub Desktop.
Save mcsee/2f7aee362e99fbe447d8c1e8aaeb9f8e to your computer and use it in GitHub Desktop.
class CartItem {
constructor(price) {
this.price = price;
}
}
class DiscountCoupon {
constructor(rate) {
this.rate = rate;
}
}
class Cart {
constructor(selecteditems, discountCoupon) {
this.items = selecteditems;
this.discountCoupon = discountCoupon;
}
subtotal() {
return this.items.reduce((previous, current) =>
previous + current.price, 0);
}
total() {
if (this.discountCoupon == null)
return this.subtotal();
else
return this.subtotal() * (1 - this.discountCoupon.rate);
}
}
cart = new Cart([
new CartItem(1),
new CartItem(2),
new CartItem(7)
], new DiscountCoupon(0.15)]);
// 10 - 1.5 = 8.5
cart = new Cart([
new CartItem(1),
new CartItem(2),
new CartItem(7)
], null);
// 10 - null = 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment