nmnikolov

04. AllThatLuggage

Jan 9th, 2015
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arg) {
  2.     var luggage = {};
  3.     var luggageSorted = {};
  4.     var sortBy = arg[arg.length - 1];
  5.  
  6.     for (var i = 0; i < arg.length - 1; i++) {
  7.         var row = arg[i].split(/\.*\*\.*/g);
  8.         var name = row[0];
  9.         var type = 'other';
  10.  
  11.         if (row[2] === 'true') {
  12.             type = 'food';
  13.         }
  14.         if (row[3] === 'true') {
  15.             type = 'drink';
  16.         }
  17.         if (!luggage.hasOwnProperty(name)) {
  18.             luggage[name] = [];
  19.         }
  20.  
  21.         luggage[name].push({
  22.             'clothe': row[1],
  23.             'kg': Number(row[5]),
  24.             'fragile': row[4] === 'true' ? true : false,
  25.             'type': type,
  26.             'transferredWith': row[6]
  27.         });
  28.     }
  29.  
  30.     var names = Object.keys(luggage);
  31.  
  32.     for (var i = 0; i < names.length; i++) {
  33.         var name = names[i];
  34.         sortLuggage(name);
  35.         luggageSorted[name] = {};
  36.  
  37.         for (var j = 0; j < luggage[name].length; j++) {
  38.             var clothe = luggage[name][j].clothe;
  39.             luggageSorted[name][clothe] = luggage[name][j];
  40.             delete luggageSorted[name][clothe].clothe;
  41.         }
  42.     }
  43.  
  44.     console.log(JSON.stringify(luggageSorted));
  45.  
  46.     function sortLuggage(name) {
  47.         luggage[name].sort(function (a, b) {
  48.             if (sortBy === 'luggage name') {
  49.                 return a.clothe > b.clothe ? 1 : -1;
  50.             } else if (sortBy === 'weight') {
  51.                 return a.kg - b.kg;
  52.             }
  53.         });
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment