Advertisement
kstoyanov

06. Travel Time js fundamentals

Jul 12th, 2020
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.  
  3.   const destinations = {};
  4.  
  5.   const travelCost = (town1, town2, destination, country) => {
  6.     const priceOne = destination[country][town1];
  7.     const priceTwo = destination[country][town2];
  8.  
  9.     return priceOne - priceTwo;
  10.   }
  11.  
  12.  
  13.   input.forEach((element) => {
  14.     let [country, town, price] = element.split(' > ').filter((e) => e !== '');
  15.  
  16.     town = town[0].toUpperCase() + town.slice(1);
  17.  
  18.     if (!destinations.hasOwnProperty(country)) {
  19.       destinations[country] = {};
  20.     }
  21.     if (!destinations[country].hasOwnProperty(town)) {
  22.       destinations[country][town] = Number(price);
  23.     }
  24.     const prevPrice = destinations[country][town];
  25.     if (prevPrice > price) {
  26.       destinations[country][town] = price;
  27.     }
  28.   });
  29.  
  30.   const orderedCountries = [...Object.keys(destinations)].sort((a, b) => a.localeCompare(b));
  31.  
  32.   let result = '';
  33.  
  34.   orderedCountries.forEach((country) => {
  35.     result += `${country} -> `;
  36.     const sortedPrices = [...Object.keys(destinations[country])].sort((a, b) => travelCost(a, b, destinations, country));
  37.     sortedPrices.forEach((town) => {
  38.       result += `${town} -> ${destinations[country][town]} `;
  39.     });
  40.     result += '\n';
  41.   });
  42.  
  43.   console.log(result);
  44.  
  45.  
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement