Reputation: 25
I'm currently learning to code and am on JavaScript. At the moment I am practicing with the use of objects by creating a random meal generator but I am very stuck. I keep getting the error "Maximum Call Stack Size Exceeded" could you please explain why and how I can fix it? Here's the code:
let menu={
_courses:{
appetizers:[],
mains:[],
desserts:[],
},
get appetizers(){
return this.appetizers;
},
set appetizers(appetizersIn){
this._courses.appetizers = appetizersIn;
},
get mains(){
return this.mains;
},
set mains(mainsIn){
this._courses.mains=mainsIn;
},
get desserts(){
return this.desserts;
},
set desserts(dessertsIn){
this._courses.desserts=dessertsIn;
},
get _courses(){
return{
appetizers: this.appetizers,
mains: this.mains,
desserts: this.desserts
}
},
addDishToCourse(courseName,dishName,dishPrice){
const dish ={
dishName,
dishPrice,
}
this._courses[courseName].push(dish);
},
getRandomDishFromCourse(courseName){
const dishes=this._courses[courseName];
const randomIndex = Math.floor(Math.random()*dishes.length);
return dishes[randomIndex];
},
generateRandomMeal: function(){
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 consists of ${appetizer.name}, ${main.name} and ${dessert.name} for dessert. That comes to a total price of £${totalPrice}`;
}
}
menu.addDishToCourse("appetizer","Garlic Mushrooms",3.50);
menu.addDishToCourse("appetizer","Garlic Bread", 2.50);
menu.addDishToCourse("appetizer","Tomato Soup",4.00);
menu.addDishToCourse("appetizer","Breadsticks and Dip",2.00);
menu.addDishToCourse("appetizer","Spicy Chicken Wings",5.00);
menu.addDishToCourse("main","Beef Lasagne",7.25);
menu.addDishToCourse("main","Vegetarian Lasagne",7.25);
menu.addDishToCourse("main","Fish and Chips",6.25);
menu.addDishToCourse("main","Hunters Chicken",7.75);
menu.addDishToCourse("main","Veggie Burger",5.50);
menu.addDishToCourse("dessert","Eton Mess",4.00);
menu.addDishToCourse("dessert","Knickerbocker Glory",3.50);
menu.addDishToCourse("dessert","Chocolate Brownies with Cream",5.00);
menu.addDishToCourse("dessert","Fruit Salad",2.50);
menu.addDishToCourse("dessert","Apple Pie and Custard",4.75);
const meal = menu.generateRandomMeal();
console.log(meal);
Thank you in advance!
Upvotes: 0
Views: 99
Reputation: 18249
You have an error here in the appetizers
getter:
return this.appetizers;
I assume you meant
return this._courses.appetizers;
to match the setters you have.
Right now you're getter essentially calls itself (because reading this.appetizers
calls your getter), so you get infinite recursion - hence the stack overflow.
Note: the same problem appears in all your other getters. The setters appear to be correct.
Upvotes: 1