Hi all. I made an alternative solution to the meal maker project, which now actually uses the courses getter. Still no setters, but there is a factory function to add meals. I think this solution is better than the official one because it doesn’t reference _courses
anywhere explicitly except the getter and factory function, but would appreciate feedback with people with more experience.
Major change is that I replaced arrays with objects as elements by pure objects
Here’s my code:
const menu = {
_courses: {
appetizers: {},
mains: {},
desserts: {},
}, //out of courses
get appetizers() {
return this._courses.appetizers;
},
get desserts() {
return this._courses.desserts;
},
get mains() {
return this._courses.mains;
},
get courses() {
return {
appetizers: this.appetizers,
mains: this.mains,
desserts: this.desserts
}
},
addDishToCourse (courseName,dishName,dishPrice) {
return this._courses[courseName][dishName] = {
name: dishName,
price: dishPrice,
}
},
getRandomDishFromCourse (courseName) {
const courses = this.courses;
const dishes = Object.assign(courses[courseName]);
const namesOfDishes = Object.keys(dishes);
const randomDish = Math.floor(Math.random()*namesOfDishes.length);
return dishes[namesOfDishes[randomDish]];
},
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('appetizers','jalapeno poppers',8);
menu.addDishToCourse('appetizers','clams on half shell',18);
menu.addDishToCourse('appetizers','pea soup',5);
menu.addDishToCourse('mains','veggie lasagna',20);
menu.addDishToCourse('mains','scallops',28);
menu.addDishToCourse('mains','stuffed mushrooms',17);
menu.addDishToCourse('desserts','tiramisu',9);
menu.addDishToCourse('desserts','fresh strawberries and cream',7);
menu.addDishToCourse('desserts','ice cream extravaganza',11);
console.log(menu.generateRandomMeal());