Lulunga

Fundamentals Final exam Practice sessions object sort

Jul 19th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let collection = {};
  3.     for (let line of input) {
  4.         if (line === 'END') {
  5.             break;
  6.         }
  7.         let [command, road, racer, nextRoad] = line.split('->');
  8.         if (command === 'Add') {
  9.             if (!collection.hasOwnProperty(road)) {
  10.                 collection[road] = [];
  11.             }
  12.             collection[road].push(racer);
  13.         } else if (command === 'Move') {
  14.  
  15.             let index = collection[road].indexOf(racer);
  16.             if (index !== -1) {
  17.                 collection[road].splice(index, 1);
  18.                 collection[nextRoad].push(racer);
  19.             }
  20.  
  21.         } else if (command === 'Close') {
  22.             if (collection.hasOwnProperty(road)) {
  23.  
  24.                 delete collection[road];
  25.             }
  26.         }
  27.  
  28.     }
  29.     let sorted = Object.entries(collection);
  30.     sorted = sorted.sort((a, b) => {
  31.         return b[1].length - a[1].length || a[0].localeCompare(b[0]);
  32.     });
  33.     console.log("Practice sessions:");
  34.     sorted.forEach(element => {
  35.  
  36.         console.log(element[0]);
  37.         let racers = element[1];
  38.         for (let name of racers) {
  39.             console.log(`++${name}`);
  40.         }
  41.  
  42.     });
  43.  
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment