Advertisement
RRusev77

TimeTravelTime

Jul 12th, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arr) {
  2.     const countries = new Map();
  3.  
  4.     for(let line of arr) {
  5.         let [country, city, price] = line.split(' > ');
  6.         if(!countries.has(country)) {
  7.             let obj = {
  8.                 [city]: Number(price),
  9.             }
  10.  
  11.             countries.set(country, obj);
  12.         } else {
  13.             if(countries.get(country)[city] != undefined) {
  14.                 let oldPrice = countries.get(country)[city];
  15.                 if(price < oldPrice) {
  16.                     countries.get(country)[city] = price;
  17.                 }
  18.             } else {
  19.                 countries.get(country)[city] = price;
  20.             }
  21.         }
  22.     }
  23.  
  24.     let sortedEntries = Array.from(countries.entries()).sort();
  25.    
  26.     sortedEntries.forEach(entrie => {
  27.         let [country, obj] = entrie;
  28.         let objectEntries = Object.entries(obj);
  29.  
  30.         if(objectEntries.length > 1) {
  31.             objectEntries = objectEntries.sort((a, b) => {
  32.                 costA = a[1];
  33.                 costB = b[1];
  34.  
  35.                 return costA - costB;
  36.             });
  37.            
  38.             let resultString = '';
  39.  
  40.             objectEntries.forEach(city => {
  41.                 let str = (city.join(' -> '));
  42.                 resultString += str + ' ';
  43.             });
  44.  
  45.             console.log(`${country} -> ${resultString}`);
  46.         } else {
  47.             let str = objectEntries[0].join(' -> ');
  48.             console.log(`${country} -> ${str}`);
  49.         }
  50.     });
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement