Advertisement
kstoyanov

03. Christmas Dinner-Exam - 10 December 2019

Oct 22nd, 2020
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class ChristmasDinner {
  2.   constructor(budget) {
  3.     this.budget = budget;
  4.     this.dishes = [];
  5.     this.products = [];
  6.     this.guests = {};
  7.   }
  8.  
  9.   get budget() {
  10.     return this._budget;
  11.   }
  12.  
  13.   set budget(value) {
  14.     if (typeof value !== 'number' || value < 0) {
  15.       throw new TypeError('The budget cannot be a negative number');
  16.     }
  17.  
  18.     this._budget = value;
  19.   }
  20.  
  21.   shopping(product) {
  22.     const type = product[0];
  23.     const price = +product[1];
  24.  
  25.     if (price > this.budget) {
  26.       throw new Error('Not enough money to buy this product');
  27.     }
  28.  
  29.     if (!this.products.includes(type)) {
  30.       this.products.push(type);
  31.     }
  32.  
  33.     this.budget -= price;
  34.  
  35.     return `You have successfully bought ${type}!`;
  36.   }
  37.  
  38.   recipes(recipe) {
  39.     const { recipeName } = recipe;
  40.     const { productsList } = recipe;
  41.  
  42.     if (productsList.length < 1) {
  43.       return;
  44.     }
  45.  
  46.     for (const product of productsList) {
  47.       if (!this.products.includes(product)) {
  48.         throw new Error('We do not have this product');
  49.       }
  50.     }
  51.  
  52.     this.dishes.push({ recipeName, productsList });
  53.  
  54.     return `${recipeName} has been successfully cooked!`;
  55.   }
  56.  
  57.   inviteGuests(name, dish) {
  58.     if (!this.dishes.map((d) => d.recipeName).includes(dish)) {
  59.       throw new Error('We do not have this dish');
  60.     }
  61.  
  62.     if (this.guests[name]) {
  63.       throw new Error('This guest has already been invited');
  64.     }
  65.  
  66.     this.guests[name] = dish;
  67.  
  68.     return `You have successfully invited ${name}!`;
  69.   }
  70.  
  71.   showAttendance() {
  72.     let result = '';
  73.     const guestsNames = Object.keys(this.guests);
  74.  
  75.     guestsNames.forEach((name) => {
  76.       const dish = this.dishes.filter((d) => d.recipeName === this.guests[name]);
  77.       result += `${name} will eat ${this.guests[name]}, which consists of ${dish[0].productsList.join(', ')}\n`;
  78.     });
  79.  
  80.     return result.trim();
  81.   }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement