Liliana797979

my viarno reshenie travel time - fundamentals

Aug 13th, 2021
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function travel(input) {
  2.     let destinations = {};
  3.  
  4.     //fill destinations
  5.     for (let element of input) {
  6.         let [country, town, cost] = element.split(" > ");
  7.  
  8.         //country does not exist
  9.         if (!Object.keys(destinations).includes(country)) {
  10.             destinations[country] = {};
  11.         }
  12.         //country exists
  13.         //town does not exist
  14.         if (!Object.keys(destinations[country]).includes(town)) {
  15.             destinations[country][town] = Number(cost);
  16.         }
  17.         //town exists
  18.         if (Number(cost) < destinations[country][town]) {
  19.             destinations[country][town] = Number(cost);
  20.         }
  21.     }
  22.     //console.log(destinations);
  23.     let sortedCountries = Object
  24.     .entries(destinations)
  25.     .sort((a, b) => a[0].localeCompare(b[0]) ||
  26.     Object.values(a[1]).reduce((x, y) => x + y) - Object.values(b[1]).reduce((x, y) => x + y));
  27.  
  28.    // console.log(sortedCountries);
  29.    for (let [country, towns] of sortedCountries) {
  30.        let townsAsEntries = Object.entries(towns).map(x => `${x[0]} -> ${x[1]}`);
  31.        console.log(`${country} -> ${townsAsEntries.join(" ")}`);
  32.    }
  33. }
  34.  
  35.  
  36. travel([
  37.     "Bulgaria > Sofia > 500",
  38.     "Bulgaria > Sopot > 800",
  39.     "France > Paris > 2000",
  40.     "Albania > Tirana > 1000",
  41.     "Bulgaria > Sofia > 200"
  42. ]);
Advertisement
Add Comment
Please, Sign In to add comment