Advertisement
kstoyanov

01. The Hungry Programmer js exam

Aug 1st, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(meals, args) {
  2.   let portions = 0;
  3.  
  4.   const shiftPlates = (first, second, arr) => {
  5.     const firstIndex = Number(first);
  6.     const secondIndex = Number(second);
  7.     if (arr[firstIndex] !== undefined && arr[secondIndex] !== undefined) {
  8.       const firstMeal = arr[firstIndex];
  9.       const secondMeal = arr[secondIndex];
  10.  
  11.       arr.splice(firstIndex, 1, secondMeal);
  12.       arr.splice(secondIndex, 1, firstMeal);
  13.     }
  14.   };
  15.  
  16.   const consumeMeals = (first, second, arr) => {
  17.     const firstIndex = Number(first);
  18.     const secondIndex = Number(second);
  19.     if (arr[firstIndex] !== undefined && arr[secondIndex] !== undefined) {
  20.       const count = secondIndex - firstIndex + 1;
  21.       arr.splice(firstIndex, count);
  22.       console.log('Burp!');
  23.       return count;
  24.     }
  25.     return 0;
  26.   };
  27.  
  28.   const infoMealCommand = (command) => {
  29.     switch (command[0]) {
  30.       case 'Serve': {
  31.         if (meals.length < 1) {
  32.           break;
  33.         }
  34.         console.log(`${meals.pop()} served!`);
  35.         break;
  36.       }
  37.       case 'Add':
  38.         if (command[1] === undefined) break;
  39.         meals.unshift(command[1]);
  40.         break;
  41.       case 'Shift':
  42.         shiftPlates(command[1], command[2], meals);
  43.         break;
  44.       case 'Eat':
  45.         if (meals.length < 1) {
  46.           break;
  47.         }
  48.         console.log(`${meals.shift()} eaten`);
  49.         portions++;
  50.         break;
  51.       case 'Consume':
  52.         portions += consumeMeals(command[1], command[2], meals);
  53.         break;
  54.       default:
  55.     }
  56.   };
  57.  
  58.   for (let i = 0; i < args.length; i++) {
  59.     const command = args[i].split(' ');
  60.     if (command == 'End') {
  61.       break;
  62.     }
  63.     infoMealCommand(command);
  64.   }
  65.   if (meals.length > 0) {
  66.     console.log(`Meals left: ${meals.join(', ')}`);
  67.   } else {
  68.     console.log('The food is gone');
  69.   }
  70.  
  71.   console.log(`Meals eaten: ${portions}`);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement