Advertisement
Niicksana

04. Breakfast Robot

Jun 6th, 2022
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. function breakfastRobot() {
  2. // apple - made with 1 carbohydrate and 2 flavour
  3. // lemonade - made with 10 carbohydrate and 20 flavour
  4. // burger - made with 5 carbohydrate, 7 fat and 3 flavour
  5. // eggs - made with 5 protein, 1 fat and 1 flavour
  6. // turkey - made with 10 protein, 10 carbohydrate, 10 fat and 10 flavour
  7. const recipes = {
  8. apple: {
  9. carbohydrate: 1,
  10. flavour: 2
  11. },
  12. lemonade: {
  13. carbohydrate: 10,
  14. flavour: 20
  15. },
  16. burger: {
  17. carbohydrate: 5,
  18. fat: 7,
  19. flavour: 3
  20. },
  21. eggs: {
  22. protein: 1,
  23. fat: 1,
  24. flavour: 1
  25. },
  26. turkey: {
  27. protein: 10,
  28. carbohydrate: 10,
  29. fat: 10,
  30. flavour: 10
  31. }
  32. };
  33.  
  34. const stock = {
  35. protein: 0,
  36. carbohydrate: 0,
  37. fat: 0,
  38. flavour: 0
  39. };
  40.  
  41. const commands = {
  42. restock,
  43. prepare,
  44. report
  45. };
  46.  
  47. return manager;
  48.  
  49. function manager(line) {
  50. const [command, param, qty] = line.split(' ');
  51. return commands[command](param, qty);
  52. };
  53.  
  54. function restock(type, qty) {
  55. stock[type] += Number(qty);
  56. return 'Success';
  57. };
  58.  
  59. function prepare(recipeAsString, qty) {
  60. qty = Number(qty);
  61.  
  62. // find recipe
  63. const recipe = Object.entries(recipes[recipeAsString]);
  64.  
  65. // calculate total ingredient quantity
  66. recipe.forEach(ingredient => ingredient[1] *= qty);
  67.  
  68. // compare one by one with stock
  69. for (let [ingredient, required] of recipe) {
  70. if (stock[ingredient] < required) {
  71. // if one is insufficient -> return error
  72. return `Error: not enough ${ingredient} in stock`;
  73. }
  74. }
  75.  
  76. // otherwise, subtract quantities from stock and return success
  77. recipe.forEach(([ingredient, required]) => stock[ingredient] -= required);
  78. return 'Success';
  79.  
  80. };
  81.  
  82. function report() {
  83. return `protein=${stock.protein} carbohydrate=${stock.carbohydrate} fat=${stock.fat} flavour=${stock.flavour}`;
  84. };
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement