kstoyanov

05. Breakfast Robot

Oct 9th, 2020
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solution() {
  2.   const stock = {
  3.     protein: 0,
  4.     carbohydrate: 0,
  5.     fat: 0,
  6.     flavour: 0,
  7.   };
  8.  
  9.   const receipts = {
  10.     apple: {
  11.       carbohydrate: 1,
  12.       flavour: 2,
  13.     },
  14.     lemonade: {
  15.       carbohydrate: 10,
  16.       flavour: 20,
  17.     },
  18.     burger: {
  19.       carbohydrate: 5,
  20.       fat: 7,
  21.       flavour: 3,
  22.     },
  23.     eggs: {
  24.       protein: 5,
  25.       fat: 1,
  26.       flavour: 1,
  27.     },
  28.     turkey: {
  29.       protein: 10,
  30.       carbohydrate: 10,
  31.       fat: 10,
  32.       flavour: 10,
  33.     },
  34.   };
  35.  
  36.   function report() {
  37.     const result = Object.keys(stock).reduce((acc, element) => {
  38.       acc.push(`${element}=${stock[element]}`);
  39.       return acc;
  40.     }, []);
  41.  
  42.     return result.join(' ');
  43.   }
  44.  
  45.   function restock(args) {
  46.     const [, product, qtty] = args;
  47.     stock[product] += +qtty;
  48.     return 'Success';
  49.   }
  50.  
  51.   function prepare(args) {
  52.     const [, food, qtty] = args;
  53.     let canPrepare = true;
  54.     const currentReceipt = Object.entries(receipts[food]);
  55.  
  56.     for (const element of currentReceipt) {
  57.       const [ingredient, qt] = element;
  58.  
  59.       if (stock[ingredient] < +qt * +qtty) {
  60.         canPrepare = false;
  61.         return `Error: not enough ${ingredient} in stock`;
  62.       }
  63.     }
  64.  
  65.     if (canPrepare) {
  66.       currentReceipt.forEach((element) => {
  67.         const [ingredient, qt] = element;
  68.  
  69.         stock[ingredient] -= +qt * +qtty;
  70.       });
  71.  
  72.       return 'Success';
  73.     }
  74.   }
  75.  
  76.   function finalResult(input) {
  77.     const args = input.split(' ');
  78.  
  79.     if (args[0] === 'report') {
  80.       return report();
  81.     }
  82.     if (args[0] === 'restock') {
  83.       return restock(args);
  84.     }
  85.     if (args[0] === 'prepare') {
  86.       return prepare(args);
  87.     }
  88.   }
  89.  
  90.   return finalResult;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment