elena1234

How to iterate through objects with map (JavaScript)

Dec 1st, 2021 (edited)
457
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solution() {
  2.     let storage = {
  3.         protein: 0,
  4.         carbohydrate: 0,
  5.         fat: 0,
  6.         flavour: 0
  7.     };
  8.  
  9.     let recipe = {
  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.     return function (text) {
  37.         let input = text.split(' ');
  38.         let command = input[0];
  39.         if (command == 'restock') {
  40.             let ingredient = input[1];
  41.             let quantity = Number(input[2]);
  42.             storage[ingredient] += quantity;
  43.             return 'Success';
  44.         } else if (command == 'prepare') {
  45.             let product = input[1];
  46.             let quantity = input[2];
  47.             return cook(product, quantity);
  48.         } else if (command == 'report') {
  49.             return returnReport(storage);
  50.         }
  51.     }
  52.  
  53.  
  54.     function cook(product, quantity) {
  55.         let result = 'Success';
  56.         for (let key in recipe[product]) {
  57.             if (recipe[product][key] * quantity > storage[key]) {
  58.                 result = `Error: not enough ${key} in stock`;
  59.                 return result;
  60.             }
  61.         }
  62.  
  63.         Object.keys(recipe[product]).map((key) => storage[key] -= (recipe[product][key] * quantity)); // NB!
  64.         return result;
  65.     }
  66.  
  67.     function returnReport(storage) {
  68.         return Object.keys(storage).map((key) => { return `${key}=${storage[key]}` }).join(' '); // NB!
  69.     }
  70. }
  71.  
  72.  
  73. let manager = solution();
  74. console.log(manager('restock protein 100'))
  75. console.log(manager('restock carbohydrate 100'))
  76. console.log(manager('restock fat 100'))
  77. console.log(manager("restock flavour 100"))
  78. console.log(manager("report"))
  79. console.log(manager('prepare apple 2'))
  80. console.log(manager('report'))
  81. console.log(manager("prepare apple 1"))
  82. console.log(manager("report"))
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
Add Comment
Please, Sign In to add comment