JavaScript Syntax: Classes Cipher help

Hi all! I’m absolutely stumped on the Shift Cipher exercise in the JavaScript Classes Syntax practice section! At the moment, my methods do not do anything but change to and from upper case. I know that there is a requirement to rotate through the alphabet, but I’m not there yet.

I think it really comes down to not understanding the true use of charCodeAt() and fromCharCode() and how to implement them in a class.

Any help would be very much appreciated!

Link to the exercise here. Third one down

// Write class below
class ShiftCipher {
  constructor(num) {
    this.num = num;
  }

encrypt(str) {
  return str.toUpperCase()
    let result = '';
    let charcode = 0;

    for (var i = 0; i < str.length; i++) {
        charcode = (str.charCodeAt(str[i])) +this.num;
        result += String.fromCharCode(charcode);
    }
    return result;
  }

  decrypt(str) {
  return str.toLowerCase()
    let result = '';
    let charcode = 0;

    for (var i = 0; i < str.length; i++) {
        charcode = (str.charCodeAt(str[i])) -this.num;
        result += String.fromCharCode(charcode);
    }
    return result;
  }

}


const cipher = new ShiftCipher(2);
console.log(cipher.encrypt('I love to code!')); // returns 'K NQXG VQ EQFG!'
console.log(cipher.decrypt('K <3 OA RWRRA')); // returns 'i  <3 my puppy'

You are using it right, but you are returning str.toUpperCase();
return stops further execution of the function, so nothing below return str.toUpperCase() will run. Remove toUpperCase and it should work.

If you want to transform your string into uppercase replace return str.toUpperCase() with str = str.toUpperCase(); instead.

The same goes with decrypt(), just remove return str.toLowerCase() or replace with str = str.toLowerCase();!

1 Like

Aha! Thanks for that. Such a simple thing. I was wondering why I wasn’t even getting an error if my code was incorrect below that. Now I know!

Can it be marked as the answer?

That way people can see that the question is already answered and is helpful for those looking for answered questions similar to their own.

1 Like