Advertisement
Guest User

Untitled

a guest
Sep 20th, 2018
1,184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. function solveTravelTime(input) {
  2. let destinations = {};
  3.  
  4. for (let i = 0; i < input.length; i++) {
  5. let [country, town, price] = input[i].split(" > ").filter(e => e !== "");
  6. price = +price;
  7. town = town[0].toUpperCase() + town.slice(1);
  8.  
  9. if (!destinations.hasOwnProperty(country)) {
  10. destinations[country] = {};
  11. }
  12. if (!destinations[country].hasOwnProperty(town)) {
  13. destinations[country][town] = price;
  14. }
  15. let prevPrice = destinations[country][town];
  16. if (prevPrice > price) {
  17. destinations[country][town] = price;
  18. }
  19. }
  20.  
  21. let orderedCountries = [...Object.keys(destinations)].sort((a,b) => a.localeCompare(b));
  22. let result = "";
  23. for (let country of orderedCountries) {
  24. result += country + " -> ";
  25. let sortedPrices = [...Object.keys(destinations[country])].sort((a, b) => travelCost(a, b, destinations, country));
  26. for (let town of sortedPrices) {
  27. result += `${town} -> ${destinations[country][town]} `;
  28. }
  29. result += "\n";
  30. }
  31. console.log(result);
  32.  
  33. function travelCost(town1, town2, destination, country) {
  34. let priceOne = destination[country][town1];
  35. let priceTwo = destination[country][town2];
  36.  
  37. return priceOne - priceTwo
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement