vladovip

08.TravelCostDestination_ Asscoc Arr_ Exercise

Mar 8th, 2022 (edited)
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function travelTime(inputArr) {
  2.   let countriesObj = {};
  3.   for (let line of inputArr) {
  4.     let [country, city, travelCost] = line.split(" > ");
  5.  
  6.     if (countriesObj.hasOwnProperty(country) == false) {
  7.       countriesObj[country] = new Map();
  8.     }
  9.     if (countriesObj[country].has(city)) {
  10.       let currentCost = countriesObj[country].get(city);
  11.       if (currentCost > travelCost) {
  12.         countriesObj[country].set(city, travelCost);
  13.       }
  14.       if (currentCost < travelCost) {
  15.         countriesObj[country].set(city, currentCost);
  16.       }
  17.     } else {
  18.       countriesObj[country].set(city, travelCost);
  19.     }
  20.   }
  21.   let sortedCountriesObjArr = Object.entries(countriesObj).sort((a, b) =>
  22.     a[0].localeCompare(b[0])
  23.   );
  24.   for (let [key, mapCollection] of sortedCountriesObjArr) {
  25.     let resultStr = `${key} ->`
  26.     let sortedMapEntries = Array.from(mapCollection.entries());
  27.     sortedMapEntries.sort((a, b) => a[1] - b[1]);
  28.     for (let [element, value] of sortedMapEntries) {
  29.         resultStr += ` ${element} -> ${value}`;
  30.     }
  31.     console.log(resultStr);
  32.   }
  33. }
  34.  
  35. travelTime([
  36.   "Bulgaria > Sofia > 500",
  37.   "Bulgaria > Sopot > 800",
  38.   "France > Paris > 2000",
  39.   "Albania > Tirana > 1000",
  40.   "Bulgaria > Sofia > 200",
  41. ]);
  42.  
  43.  
  44. console.log(`***********`);
  45.  
  46.  
  47. travelTime([
  48.   'Bulgaria > Sofia > 25000',
  49.   'Bulgaria > Sofia > 25000',
  50.   'Kalimdor > Orgrimar > 25000',
  51.   'Albania > Tirana > 25000',
  52.   'Bulgaria > Varna > 25010',
  53.   'Bulgaria > Lukovit > 10'
  54.   ]
  55.   );
  56.  
  57.  
Add Comment
Please, Sign In to add comment