Advertisement
dimipan80

Exams - Logs Aggregator

Nov 13th, 2014
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* You are given a sequence of access logs in format <IP> <user> <duration>. Write a program to aggregate
  2. the logs data and print for each user the total duration of his sessions and a list of unique IP addresses
  3. in format "<user>: <duration> [<IP1>, <IP2>, …]". Order the users alphabetically.
  4. Order the IPs alphabetically. */
  5.  
  6. function aggregator(arr) {
  7.     var countLogs = Number(args[0]);
  8.     var aggregator = {};
  9.     var i;
  10.     for (i = 0; i < countLogs; i += 1) {
  11.         var logLine = args[i + 1].split(/\s+/).filter(Boolean);
  12.         var IPaddress = logLine[0].trim();
  13.         var user = logLine[1].trim();
  14.         var duration = Number(logLine[2]);
  15.  
  16.         if (!(aggregator.hasOwnProperty(user))) {
  17.             aggregator[user] = { duration: 0, IP_addresses: [] };
  18.         }
  19.  
  20.         aggregator[user].duration += duration;
  21.         if (aggregator[user].IP_addresses.indexOf(IPaddress) < 0) {
  22.             aggregator[user].IP_addresses.push(IPaddress);
  23.         }
  24.     }
  25.  
  26.     var sortedNames = Object.keys(aggregator).sort();
  27.     for (i = 0; i < sortedNames.length; i += 1) {
  28.         if (aggregator.hasOwnProperty(sortedNames[i])) {
  29.             aggregator[sortedNames[i]].IP_addresses.sort();
  30.             console.log("%s: %s [%s]", sortedNames[i], aggregator[sortedNames[i]].duration,
  31.                 aggregator[sortedNames[i]].IP_addresses.join(', '));
  32.         }
  33.     }
  34. }
  35.  
  36. aggregator(['7',
  37.     '192.168.0.11 peter 33',
  38.     '10.10.17.33 alex 12',
  39.     '10.10.17.35 peter 30',
  40.     '10.10.17.34 peter 120',
  41.     '10.10.17.34 peter 120',
  42.     '212.50.118.81 alex 46',
  43.     '212.50.118.81 alex 4'
  44. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement