maymunskoa

Song Encryption (Final Exam 240719)

Mar 25th, 2020
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.   const namePattern = /^[A-Z][a-z ']+$/m;
  3.   const songPattern = /^[A-Z\s]+$/gm;
  4.  
  5.   const encrypt = (name, key) => {
  6.     let str = "";
  7.     for (const letter of name) {
  8.       let newcode = letter.charCodeAt() + key;
  9.       if (letter.charCodeAt() > 64 && letter.charCodeAt() < 91) {
  10.         //A-Z
  11.         if (newcode > 90) {
  12.           let diff = newcode - 90;
  13.           newcode = 64 + diff;
  14.         }
  15.         str += String.fromCharCode(newcode);
  16.       } else if (letter.charCodeAt() > 96 && letter.charCodeAt() < 123) {
  17.         //a-z
  18.         if (newcode > 122) {
  19.           let diff = newcode - 122;
  20.           newcode = 96 + diff;
  21.         }
  22.         str += String.fromCharCode(newcode);
  23.       } else {
  24.         str += letter;
  25.       }
  26.     }
  27.     return str;
  28.   };
  29.  
  30.   for (const line of input) {
  31.     if (line === "end") {
  32.       break;
  33.     }
  34.     let [artist, song] = line.split(":");
  35.     artist = artist.trim();
  36.     song = song.trim();
  37.     if (
  38.       artist.match(namePattern) !== null &&
  39.       song.match(songPattern) !== null
  40.     ) {
  41.       let key = artist.length;
  42.       let encName = encrypt(artist, key);
  43.       let encSong = encrypt(song, key);
  44.       console.log(`Successful encryption: ${encName}@${encSong}`);
  45.     } else {
  46.       console.log(`Invalid input!`);
  47.     }
  48.   }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment