Skip to content

Instantly share code, notes, and snippets.

@ms314006
Last active September 25, 2022 02:12
Show Gist options
  • Save ms314006/691bab1f9ba8f42403e347a592692e38 to your computer and use it in GitHub Desktop.
Save ms314006/691bab1f9ba8f42403e347a592692e38 to your computer and use it in GitHub Desktop.
class Box {
constructor() {
this.price = 50;
this.products = [];
}
get totalPrice() {
const productsTotalPrice = this.products.reduce(
(totalPrice, product) => totalPrice + product.price, 0
);
return productsTotalPrice + this.price;
}
addProduct(product) {
this.products.push(product);
}
}
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const pen = new Product('pen', 60);
const eraser = new Product('eraser', 20);
const box = new Box();
box.addProduct(pen);
box.addProduct(pen);
box.addProduct(pen);
box.addProduct(eraser);
box.totalPrice; // 250
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment