Advertisement
YavorGrancharov

Hungry Programmer

Feb 6th, 2018
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function hungry(meals, commands) {
  2.     let count = 0;
  3.     for (let command = 0; command < commands.length; command++) {
  4.         let firstPortion = meals[0];
  5.         let served = meals[meals.length - 1];
  6.         if (commands[command] === 'End') {
  7.             break;
  8.         }
  9.         if (commands[command] === 'Serve') {
  10.             if (meals.length > 0) {
  11.                 console.log(`${served} served!`);
  12.                 let currentIndex = meals.indexOf(served);
  13.                 if (currentIndex > -1) {
  14.                     meals.splice(currentIndex, 1);
  15.                 }
  16.             }
  17.         }
  18.         if (commands[command] === 'Eat') {
  19.             if (meals.length > 0) {
  20.                 console.log(`${firstPortion} eaten`);
  21.                 count++;
  22.                 let currentIndex = meals.indexOf(firstPortion);
  23.                 if (currentIndex > -1) {
  24.                     meals.splice(currentIndex, 1);
  25.                 }
  26.             }
  27.         }
  28.         if (commands[command].split(/\s/)[0] === 'Add') {
  29.             let newMeal = commands[command].split(/\s/)[1];
  30.             if (newMeal !== '' && newMeal !== undefined) {
  31.                 meals.unshift(newMeal);
  32.             }
  33.         }
  34.         if (commands[command].split(/\s/)[0] === 'Consume') {
  35.             if (meals.length > 0) {
  36.                 let splicedArr = [];
  37.                 let startIndex = Number(commands[command].split(/\s/)[1]);
  38.                 let endIndex = Number(commands[command].split(/\s/)[2]);
  39.                 if (startIndex >= 0 && endIndex < meals.length) {
  40.                     console.log('Burp!');
  41.                     splicedArr = meals.splice(startIndex, endIndex - startIndex + 1);
  42.                 }
  43.                 count += splicedArr.length;
  44.             }
  45.         }
  46.         if (commands[command].split(/\s/)[0] === 'Shift') {
  47.             let startIndex = Number(commands[command].split(/\s/)[1]);
  48.             let endIndex = Number(commands[command].split(/\s/)[2]);
  49.             if (startIndex >= 0 && endIndex < meals.length) {
  50.                 let temp = meals[startIndex];
  51.                 meals[startIndex] = meals[endIndex];
  52.                 meals[endIndex] = temp;
  53.             }
  54.         }
  55.     }
  56.     if (meals.length !== 0) {
  57.         console.log(`Meals left: ${meals.join(', ')}`);
  58.     } else {
  59.         console.log('The food is gone');
  60.     }
  61.     console.log(`Meals eaten: ${count}`);
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement