Todorov_Stanimir

06. Travel Time with Map

Jul 10th, 2019
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function travelTime(input) {
  2.     let countries = new Map();
  3.     input.forEach(line => {
  4.         let [country, town, price] = line.split(' > ');
  5.         price = Number(price);
  6.         if (!(countries.has(country))) {
  7.             countries.set(country, [{ [town]: price }]);
  8.         } else {
  9.             let townNotExist = true;
  10.             countries.get(country).forEach((currentTown, index) => {
  11.                 if (Object.keys(currentTown)[0] === town) {
  12.                     townNotExist = false;
  13.                     if (Object.values(currentTown)[0] > price) {
  14.                         countries.get(country).splice(index, 1, { [town]: price });
  15.                     }
  16.                 }
  17.             });
  18.             if (townNotExist) {
  19.                 countries.get(country).push({ [town]: price });
  20.             }
  21.         }
  22.     });
  23.     let result = [...countries].sort((a, b) => a[0].localeCompare(b[0]));
  24.  
  25.     result.forEach(line => {
  26.         let arrayTowns = line[1]
  27.             .sort((a, b) => a.town - b.town)
  28.             .map(town => `${Object.keys(town)[0]} -> ${Object.values(town)[0]}`);
  29.         console.log(`${line[0]} -> ${arrayTowns.join(' ')}`);
  30.     })
  31. }
  32. travelTime([
  33.     "Bulgaria > Sofia > 500",
  34.     "Bulgaria > Sopot > 800",
  35.     "France > Paris > 2000",
  36.     "Albania > Tirana > 1000",
  37.     "Bulgaria > Sofia > 200"
  38. ])
Advertisement
Add Comment
Please, Sign In to add comment