didkoslawow

Untitled

Mar 4th, 2023
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function travelTime(input) {
  2.   const countries = {};
  3.  
  4.   input.forEach((countryInput) => {
  5.     const town = {};
  6.     const countryInfo = countryInput.split(' > ');
  7.     const countryName = countryInfo[0];
  8.     const townName = countryInfo[1];
  9.     const value = Number(countryInfo[2]);
  10.  
  11.     if (!countries.hasOwnProperty(countryName)) {
  12.       town[townName] = value;
  13.       countries[countryName] = town;
  14.     } else {
  15.       if (!countries[countryName].hasOwnProperty(townName)) {
  16.         town[townName] = value;
  17.         countries[countryName][townName] = value;
  18.       } else {
  19.         const currentValue = countries[countryName][townName];
  20.         countries[countryName][townName] = value;
  21.         if (currentValue <= countries[countryName][townName]) {
  22.           countries[countryName][townName] = currentValue;
  23.         }
  24.       }
  25.     }
  26.   });
  27.  
  28.   const sortedCountries = Object.entries(countries).sort((a, b) =>
  29.     a[0].localeCompare(b[0])
  30.   );
  31.  
  32.   sortedCountries.forEach((element) => {
  33.     const townSorted = Object.entries(element[1])
  34.       .sort((a, b) => a[1] - b[1])
  35.       .map((town) => town.join(' -> '));
  36.     console.log(`${element[0]} -> ${townSorted.join(' ')}`);
  37.   });
  38. }
Add Comment
Please, Sign In to add comment