Advertisement
dimipan80

Exams - Cloud Manager

Nov 22nd, 2014
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a program that reads file information from the console and groups the files according to their extensions
  2. in the format <file-extension> <[file1, file2, … ]> <total memory in MB>, where total memory is the sum of
  3. the sizes of the respective files. Extension lines should be sorted by the extension names. The files themselves
  4. should also be ordered alphabetically. Finally, the information is converted to JSON format and printed.
  5. The input is passed as array of several strings: each string will contain information about a file in
  6. the format <name> <extension> <memory>, separated by spaces. Print the file information in JSON format.
  7. The memory should be printed with 2 places after the decimal point.*/
  8.  
  9. "use strict";
  10.  
  11. function formatFiles(arr) {
  12.     var cloudMap = {};
  13.     for (var i = 0; i < arr.length; i += 1) {
  14.         arr[i] = arr[i].split(/\s+/g).filter(Boolean);
  15.         var fileName = arr[i][0];
  16.         var extension = arr[i][1];
  17.         var memory = parseFloat(arr[i][2]);
  18.  
  19.         if (!(extension in cloudMap)) {
  20.             cloudMap[extension] = { 'files': [], 'memory': 0 };
  21.         }
  22.         cloudMap[extension].files.push(fileName);
  23.         cloudMap[extension].memory += memory;
  24.     }
  25.  
  26.     function sortingObject(object) {
  27.         var sortedKeys = Object.keys(object).sort();
  28.         var sortedObj = {};
  29.         for (var i = 0; i < sortedKeys.length; i += 1) {
  30.             if (object.hasOwnProperty(sortedKeys[i])) {
  31.                 sortedObj[sortedKeys[i]] = {};
  32.                 sortedObj[sortedKeys[i]].files = object[sortedKeys[i]].files.sort();
  33.                 sortedObj[sortedKeys[i]].memory = object[sortedKeys[i]].memory.toFixed(2);
  34.             }
  35.         }
  36.  
  37.         return sortedObj;
  38.     }
  39.  
  40.     cloudMap = sortingObject(cloudMap);
  41.  
  42.     return JSON.stringify(cloudMap);
  43. }
  44.  
  45. console.log(formatFiles([
  46.     'sentinel .exe 15MB',
  47.     'zoomIt .msi 3MB',
  48.     'skype .exe 45MB',
  49.     'trojanStopper .bat 23MB',
  50.     'kindleInstaller .exe 120MB',
  51.     'setup .msi 33.4MB',
  52.     'winBlock .bat 1MB'
  53. ]));
  54.  
  55. console.log(formatFiles([
  56.     'eclipse .tar.gz 198.00MB',
  57.     'uTorrent .gyp 33.02MB',
  58.     'nodeJS .gyp 14MB',
  59.     'nakov-naked .jpeg 3MB',
  60.     'gnuGPL .pdf 5.6MB',
  61.     'skype .tar.gz 66MB',
  62.     'selfie .jpeg 7.24MB',
  63.     'myFiles .tar.gz 783MB'
  64. ]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement