I have this all working after following along with the video, but I’m not totally clear on WHY it works. My two questions are:
-
the “dish” object that is created on line 33: Why am I able to access it from other places? I thought this was part of a code block and therefore not globally accessible?
-
The setters on lines 16 - 24. I had thought that using a syntax like this.array = 1 would completely overwrite the array and that I should be using a .push or .append or something similar. But when the code is run at the end and I reuse the setter multiple times it seems to simply add to the array. Have I misunderstood the behaviour of the ‘=’ in this context?
Thanks!
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.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 courseFoods = this._courses[courseName];
let courseIndex = Math.random()*courseFoods.length;
courseIndex = Math.floor(courseIndex);
// console.log(dishes.length);
// console.log(dishes);
// console.log(index);
return courseFoods[courseIndex];
},
generateRandomMeal() {
const appetizer = menu.getRandomDishFromCourse('appetizers');
const main = menu.getRandomDishFromCourse('mains');
const dessert = menu.getRandomDishFromCourse('desserts');
const totalPrice = appetizer.price + main.price + dessert.price;
console.log(appetizer.price)
return `Your meal is ${appetizer.name}, then ${main.name}, then ${dessert.name}. It will cost \$${totalPrice}`
}
};
// menu.addDishToCourse('mains', 'water', 5)
// console.log(menu.courses);
menu.addDishToCourse('appetizers', 'salad', 4.50);
menu.addDishToCourse('appetizers', 'wings', 5.00);
menu.addDishToCourse('appetizers', 'fries', 7.50);
menu.addDishToCourse('mains', 'burger', 12.15);
menu.addDishToCourse('mains', 'tofu', 13.32);
menu.addDishToCourse('mains', 'curry', 15.20);
menu.addDishToCourse('desserts', 'ice cream', 7.60);
menu.addDishToCourse('desserts', 'cookies', 6.80);
menu.addDishToCourse('desserts', 'tea', 3.75);
const meal = menu.generateRandomMeal();
console.log(meal);