Liliana797979

travel time - fundamentals

Aug 13th, 2021
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function travelTime(input) {
  2.     let countries = {};
  3.  
  4.     input.forEach(element => {
  5.         let [country, town, currentPrice] = element.split(" > ");
  6.         currentPrice = Number(currentPrice);
  7. if (!(countries.hasOwnProperty(country)) {
  8.     countries[country] = {};
  9.     countries[country][town] = currentPrice;
  10. } else {
  11.     let countryObj = countries[country];
  12.     if (!countryObj.hasOwnProperty(town)) {
  13.         countryObj[town] = currentPrice;
  14.     } else {
  15.         let oldPrice = countryObj[town];
  16.         if (oldPrice > currentPrice) {
  17.             countryObj[town] = currentPrice;
  18.         }
  19.     }
  20. }
  21.  
  22.     });
  23.        
  24. let sortCountries = Object.entries(countries)
  25. .sort(sortCountries);
  26.  
  27. for (let [name, towns] of sortCountries) {
  28.     let sortTowns = Object.entries(towns).sort(sortTowns);
  29.     let output = ` ${name} ->` ;
  30.     for (const [townName, townPrice] of sortTowns) {
  31.         output += `${townName} -> ${townPrice}`;
  32.     }
  33.     console.log(output);
  34. }
  35.        
  36. function sortCountries(firstCountry, secondCountry) {
  37.     let firstName = firstCountry[0];
  38.     let secondName = secondCountry[0];
  39.  
  40.     return firstName.localeCompare(secondCountry);
  41. }
  42.  
  43. function sortTowns(firstTown, secondTown) {
  44.     let firstPrice = firstTown[1];
  45.     let secondPrice = secondTown[1];
  46.  
  47.     return firstPrice - secondPrice;
  48. }        
  49.  
  50. travelTime([
  51.     "Bulgaria > Sofia > 500",
  52.     "Bulgaria > Sopot > 800",
  53.     "France > Paris > 2000",
  54.     "Albania > Tirana > 1000",
  55.     "Bulgaria > Sofia > 200"
  56. ]);
Advertisement
Add Comment
Please, Sign In to add comment