AlexanderHristov

Problem 4 - Iron Girder

Dec 11th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function ironGirder(inputArr) {
  2.  
  3.     let regEx = /(.*):(\d+|\w+)->(\d+)/;
  4.     let destinationsObj = {};
  5.     let dataObj = {};
  6.  
  7.     for (let currentString of inputArr) {
  8.  
  9.         if (currentString === 'Slide rule') {
  10.             break;
  11.         } else {
  12.  
  13.             let [, city, time, passengers] = currentString.match(regEx);
  14.  
  15.             if (!destinationsObj.hasOwnProperty(city) && time !== 'ambush') {
  16.                 destinationsObj[city] = {};
  17.                 dataObj = destinationsObj[city];
  18.                 dataObj['time'] = +time;
  19.                 dataObj['passengers'] = +passengers;
  20.  
  21.             } else if (destinationsObj.hasOwnProperty(city) && time !== 'ambush') {
  22.  
  23.                 if (destinationsObj[city].time > +time || destinationsObj[city].time === 0) {
  24.                     destinationsObj[city].time = +time;
  25.                 }
  26.  
  27.                 destinationsObj[city].passengers += +passengers;
  28.  
  29.             } else if (destinationsObj.hasOwnProperty(city) && time === 'ambush') {
  30.  
  31.                 destinationsObj[city].time = 0;
  32.                 destinationsObj[city].passengers -= +passengers;
  33.             }
  34.         }
  35.     }
  36.  
  37.     let cityKeysArr = Object.keys(destinationsObj);
  38.  
  39.     for (let cityKey of cityKeysArr) {
  40.         if (destinationsObj[cityKey].time === 0 || destinationsObj[cityKey].passengers <= 0) {
  41.             delete destinationsObj[cityKey];
  42.         }
  43.     }
  44.  
  45.     let result = Object.entries(destinationsObj).sort(sortObject);
  46.  
  47.     result.forEach(x => console.log(`${x[0]} -> Time: ${x[1].time} -> Passengers: ${x[1].passengers}`));
  48.  
  49.     function sortObject(a, b) {
  50.  
  51.         let [aKey, aValue] = a;
  52.         let [bKey, bValue] = b;
  53.  
  54.         let firstCriteria = aValue.time - bValue.time;
  55.  
  56.         if (firstCriteria === 0) {
  57.             return aKey.localeCompare(bKey);
  58.         }
  59.  
  60.         return firstCriteria;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment