Javascript Classes - Issues with ShiftCipher Problem

Hello! First time poster here. I have been working on this ShiftCipher problem all day and I still can’t get it to work properly. Below is what I’ve come up with with a lot of help from the internet however the output is incorrect. Any insights would be much appreciated.
Link to Exercise - Number 3 of 3

``````class ShiftCipher {
constructor(num){
this.num = num;
}

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

for (var i = 0; i < str.length; i++) {
let c = (str[i])

// To make sure it's a letter
if (c.match(/[a-z]/i)) {

// Get the letter's code
var code = str.charCodeAt(i);

// Unicode for uppercase letters
if (code >= 65 && code <= 90) {
c = String.fromCharCode(((code - 65 + this.num) % 26) + 65);
}
}
result += c;
}
console.log(result);
};

decrypt(str){

str = str.toLowerCase();
let result = '';

for (var i = 0; i < str.length; i++) {
let c = (str[i])

// To make sure it's a letter...
if (c.match(/[a-z]/i)) {

// Get the letter's code
var code = str.charCodeAt(i);

// Unicode for lowercase letters
if (code >= 97 && code <= 122) {
c = String.fromCharCode(((code - 97 - this.num) % 26) + 97);
}
}
result += c;
}
console.log(result);
};
}
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'
``````

The output I get is:
K NQXG VQ EQFG!
i <3 m_ pupp_

With this error message when I click on CheckAnswer: Tested method `encrypt('Z')` with a shift of `1` , expected `'A'` . In the `encrypt()` method, did you handle wrapping around to the beggining(sic) of the alphabet?

Hi @css6097359680
so the encrypt method is returning the expected result. But the calculation

doesn’t work backwards. If you subtract this.num instead of adding it, `(code - 97 - this.num) % 26` returns a value below zero. I don’t know how to fix it with your construction, you could simply add 26 if `code - 97 - this.num` returns a value below 0.

Also you’re passing an uppercase string to the decrypt method. So you could use the same unicode numbers as in the decrypt method and apply .toLowerCase() after the shifting.

Thank you @mirja_t . I tried what you suggested and a few other things but to no avail. I appreciate you taking the time to help!

If you’re still on it, would you like to post your new code? Since your decrypt method works, you’re close…

Honestly I put it aside and moved on in the full-stack course. Thought I would revisit it once I became more proficient at writing code! Thank you again for offering to help

1 Like