Skip to content

Instantly share code, notes, and snippets.

@debonx
Last active August 27, 2019 15:12
Show Gist options
  • Save debonx/fc228fdb44dcc29375e49e8bf784e046 to your computer and use it in GitHub Desktop.
Save debonx/fc228fdb44dcc29375e49e8bf784e046 to your computer and use it in GitHub Desktop.
Practicing JS advanced objects through a meal generator. You'll get an appetizer, a main and a dessert. Is it enough?
// Creating Menu
const menu = {
_courses: {
appetizers: [],
mains: [],
desserts: []
},
get courses(){
return {
appetizers: this.appetizers,
mains: this.mains,
desserts: this.desserts
};
},
get appetizers(){
return this._courses.appetizers;
},
set appetizers(appetizerIn) {
if(typeof appetizerIn == 'object'){
this._courses.appetizers.push(appetizerIn);
} else {
console.log('Please specify an appetizer');
}
},
get mains(){
return this._courses.mains;
},
set mains(mainIn) {
if(typeof mainIn == 'object'){
this._courses.mains.push(mainIn);
} else {
console.log('Please specify a main');
}
},
get desserts() {
return this._courses.desserts;
},
set desserts(dessertIn) {
if(typeof dessertIn == 'object'){
this._courses.desserts.push(dessertIn);
} else {
console.log('Please specify a dessert');
}
},
addDishToCourse(courseName, dishName, dishPrice){
const dish = {
name: dishName,
price: 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 is ${appetizer.name}, ${main.name}, ${dessert.name}. The price is ${totalPrice}.`;
}
};
menu.addDishToCourse('appetizers', 'Caesar salad', 4.25);
menu.addDishToCourse('appetizers', 'Caprese', 3.25);
menu.addDishToCourse('appetizers', 'Salmon salad', 6.25);
menu.addDishToCourse('mains', 'Pasta with cherry tomatoes', 6.25);
menu.addDishToCourse('mains', 'Pizza Margherita', 7.25);
menu.addDishToCourse('mains', 'Rice with truffles', 8.25);
menu.addDishToCourse('desserts', 'Panna cotta', 2.25);
menu.addDishToCourse('desserts', 'Tiramisu', 5.25);
menu.addDishToCourse('desserts', 'Lemon cake', 6.25);
// Generating random meal
const meal = menu.generateRandomMeal();
console.log(meal);
// Testing setter
menu.desserts = {
name: 'Ice Cream',
price: 2.50
};
// Logging new dessert menu
console.log(menu.desserts);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment