OOP (JS) - sjherrick/code-base GitHub Wiki

OOP (JS)

Getters/setters

  • Example
const menu = {
  _courses: {
    appetizers: [],
    mains: [],
    desserts: []
  },
  get appetizers() {
    return this._courses.appetizers;
  },
  set appetizers(food) {
    this._courses.appetizers = food;
  },
  get mains() {
    return this._courses.mains;
  },
  set mains(food) {
    this._courses.mains = food;
  },
  get desserts() {
    return this._courses.desserts;
  },
  set desserts(food) {
    this._courses.desserts = food
  },
  get courses() {
    return {
      appetizers: this.appetizers,
      mains: this.mains,
      desserts: this.desserts
    }
  },
  addDishToCourse(courseName, dishName, dishPrice) {
    const dish = {
      name: dishName,
      price: dishPrice
    }
    return this._courses[courseName].push(dish);
  },
  getRandomDishFromCourse(courseName) {
    const dishes = this._courses[courseName];
    const randomIndex = Math.floor(Math.random() * dishes.length)
    return dishes[randomIndex];
  },
  generateRandomMeal() {
    const appetizers = this.getRandomDishFromCourse('appetizers');
    const mains = this.getRandomDishFromCourse('mains');
    const desserts = this.getRandomDishFromCourse('desserts');
    const totalPrice = appetizers.price + mains.price + desserts.price;

    return `Your meal is ${appetizers.name}, ${mains.name}, and ${desserts.name}. The price is $${totalPrice}.`;
  }
}

menu.addDishToCourse('appetizers', 'tuna tartare', 8.50);
menu.addDishToCourse('appetizers', 'escargot', 17);
menu.addDishToCourse('appetizers', 'dynamite roll', 22);

menu.addDishToCourse('mains', 'filet mignon', 38.50);
menu.addDishToCourse('mains', 'lobster', 33);
menu.addDishToCourse('mains', 'brick chicken', 24);

menu.addDishToCourse('desserts', 'peanut butter pie', 8);
menu.addDishToCourse('desserts', 'bundt cake', 10.50);
menu.addDishToCourse('desserts', 'ice cream', 4);
let meal = menu.generateRandomMeal();
console.log(meal);