# JavaScript Practice: Classes Problem 3

Hi everyone! This is my take on the Javascript Practice Classes syntax.

Problem 3

When asked to wrap to the beginning of the alphabet once the character’s UTF 16 code is over 90, this is
the provided solution:

if (charNum > 90) {
charNum -= 26;

But once charNum reaches 117, this wouldn’t work (90 (‘Z’) + 26 (Amount of letters) = 116) . So I came up with a way to always wrap back to the beginning of the alphabet even when it passes 116.

// Write class below class ShiftCipher{ constructor(shift){ this._shift = shift; } encrypt(sentence){ const upperCase = sentence.toUpperCase(); let newSentence = ""; for (let i = 0; i<upperCase.length; i++){ // Get character's UTF-16 code let char = upperCase.charCodeAt(i) ; // If it's uppercase alphabet, adds 2 to the UTF-16 code if(char >= 65 && char <= 90 ){ char += this._shift; // If char goes more than 90, which is the UTF-16 code of 'Z', it wraps to the beginning of the alphabet. if (char > 90){ // Calculates distance between 90 and the character's new UTF 16 code. const distance = char - 90; // Round up the result of dividing the distance by 26 (how many letters in the alphabet) to calculate how many cycle of going through the alphabet does it take to reach the new character. const cycle = Math.ceil(distance/26); // Alphabet multiplied by the cycle const alphabetCycle = 26 * cycle; // Calculate the new UTF-16 code after wrapping if code goes over 90 const newChar = char - alphabetCycle; newSentence += String.fromCharCode(newChar); } else{ newSentence += String.fromCharCode(char); } } else{ newSentence += String.fromCharCode(char); } } return newSentence; } decrypt(sentence){ const lowerCase = sentence.toLowerCase(); let newSentence = ""; for (let i = 0; i<lowerCase.length; i++){ // Get character's UTF-16 code let char = lowerCase.charCodeAt(i); // If it's lowercase alphabet, substracts 2 to the UTF-16 code if(char >= 97 && char <= 122 ){ char -= this._shift; // If char goes less than 97, which is the UTF-16 code of 'a', it wraps to the end of the alphabet. if (char < 97){ // Calculates distance between 97 and the character's new UTF 16 code. const distance = 97 - char; // Round up the result of dividing the distance by 26 (how many letters in the alphabet) to calculate how many cycle of going through the alphabet does it take to reach the new character. const cycle = Math.ceil(distance/26); // Alphabet multiplied by the cycle const alphabetCycle = 26 * cycle; // Calculate the new UTF-16 code after wrapping if code goes under 97 const newChar = char + alphabetCycle; newSentence += String.fromCharCode(newChar); } else{ newSentence += String.fromCharCode(char); } } else{ newSentence += String.fromCharCode(char); } } return newSentence; } } const cipher = new ShiftCipher(2); cipher.encrypt('I love to code!'); // returns 'K NQXG VQ EQFG!' cipher.decrypt('K <3 OA RWRRA'); // returns 'i <3 my puppy'
1 Like