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?