Meal maker Error

Hi guys, I am working on the Meal Maker project, my full code here:


const menu = {
  _courses:{
    appetizers: [],
    mains: [],
    desserts: [],
  },
  get appetizers() {
    return this._courses.appetizers;
  },
  get mains() {
    return this._courses.mains;
  },
  get desserts() {
    return this._courses.desserts;
  },
  set appetizers(appetizers){
    this._courses.appetizers = appetizers;
  },
  set mains(mains){
    this._courses.mains = mains;
  },
  set desserts(desserts){
    this._courses.desserts = desserts;
  },
  get _courses() {
    return {
      appetizers: this._courses.appetizers,
      mains: this._courses.mains,
      desserts: this._courses.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 appetizer = this.getRandomDishFromCourse('appetizers');
    const main = this.getRandomDishFromCourse('mains');
    const dessert = this.getRandomDishFromCourse('desserts');
    const totalPrice = appetizer.price + main.price + dessert.price
    return `Your meal is ${appetizer.name}, ${main.name}, and ${dessert.name}. The total price is ${totalPrice}`
  }
}
menu.addDishToCourse('appetizer.name', 'salad', 4.00)

This rendered a RangeError: Maximum call stack size exceeded at at Object.get _courses [as _courses] (/home/ccuser/workspace/learn-javascript-objects-meal-maker/app.js:27:5) but I cannot find where it went wrong.

I would really appreciate your help!

this error occurs when a function/method keeps calling itself, until the maximum depth is reached

in your case, this is the method bound to the _courses getter property

if you look at the getter:

  get _courses() {
    return {
      appetizers: this._courses.appetizers,
      mains: this._courses.mains,
      desserts: this._courses.desserts,
    }
  },

you can see the getter (get _courses) and the property you try access (this._courses) have the same name, resulting in endless calls to the method bound to the getter property

2 Likes