Advertisement
kstoyanov

03. The Pianist js exam

Aug 15th, 2020
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(args) {
  2.   const numberOfPieces = Number(args.shift());
  3.   const pieces = {};
  4.  
  5.  
  6.   for (let i = 0; i < numberOfPieces; i++) {
  7.     const element = args[i];
  8.  
  9.     const [piece, composer, key] = element.split('|');
  10.  
  11.     pieces[piece] = { composer, key };
  12.   }
  13.  
  14.   let lineInput = args.shift();
  15.  
  16.   while (lineInput !== 'Stop') {
  17.     const [command, piece, composer, key] = lineInput.split('|');
  18.  
  19.     switch (command) {
  20.       case 'Add':
  21.  
  22.         if (Object.prototype.hasOwnProperty.call(pieces, piece)) {
  23.           console.log(`${piece} is already in the collection!`);
  24.         } else {
  25.           pieces[piece] = { composer, key };
  26.           console.log(`${piece} by ${composer} in ${key} added to the collection!`);
  27.         }
  28.  
  29.         break;
  30.       case 'Remove':
  31.  
  32.         if (Object.prototype.hasOwnProperty.call(pieces, piece)) {
  33.           delete pieces[piece];
  34.           console.log(`Successfully removed ${piece}!`);
  35.         } else {
  36.           console.log(`Invalid operation! ${piece} does not exist in the collection.`);
  37.         }
  38.  
  39.  
  40.         break;
  41.       case 'ChangeKey':
  42.         if (Object.prototype.hasOwnProperty.call(pieces, piece)) {
  43.           pieces[piece].key = composer;
  44.           console.log(`Changed the key of ${piece} to ${composer}!`);
  45.         } else {
  46.           console.log(`Invalid operation! ${piece} does not exist in the collection.`);
  47.         }
  48.         break;
  49.  
  50.       default:
  51.         break;
  52.     }
  53.  
  54.     lineInput = args.shift();
  55.   }
  56.  
  57.   Object.entries(pieces)
  58.     .sort((a, b) => a[0].localeCompare(b[0]) || a[1].composer.localeCompare(b[1].composer))
  59.     .forEach((el) => {
  60.       const [piece, props] = el;
  61.       const { composer, key } = props;
  62.       console.log(`${piece} -> Composer: ${composer}, Key: ${key}`);
  63.     });
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement