Hi everyone,
I’m stuck on the answer to question 3 of this Javascript Quiz
I tried to test again and again the problem pop-up when I checked the answer, my codes work fine for the test, but it keeps saying something wrong.
Did I miss something here?
A shift cipher takes a plain text message and shifts each letter forward in the alphabet by a given number. For example, a shift cipher with a shift of 1
would turn the string 'hello'
to 'ifmmp'
.
Create a class ShiftCipher
that takes the numerical value of the shift as a constructor parameter. The class should have two methods:
-
encrypt
: takes a plain text string and returns a capitalized string with each letter shifted forward in the alphabet based on the set shift value. -
decrypt
: takes an encrypted message and returns a lower case string with each letter shifted back in the alphabet based on the set shift value. - In both methods, any character outside the alphabet should remain the same.
- But if a character is shifted outside the alphabet in either direction it should be wrapped around to the other side. For example, encrypting a
y
with a shift of4
results inC
and decrypting anA
with a shift of1
result inz
.
Example:
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'
Feel free to reference the Unicode Table as well as the JavaScript String methods including: toUpperCase()
, toLowerCase()
, charCodeAt()
and fromCharCode()
This is my solution:
// Write class below
class ShiftCipher {
constructor(number) {
this._number = number;
}
encrypt(string) {
let upperString = string.toUpperCase();
let charCode = [];
for (let i = 0; i<upperString.length;i++) {
charCode.push(upperString[i].charCodeAt());
}
let newCharCode = charCode.map(x => {
if (x > 64 && x < 91 && this._number > 90-x) {
return 64 + this._number -(90-x);
} else if (x > 64 && x < 91) {
return x + this._number;
} else return x ;
})
let newString = "";
newCharCode.forEach(x => newString += String.fromCharCode(x));
return console.log(newString);
}
decrypt(string) {
let lowerString = string.toLowerCase();
let charCode = [];
for (let i = 0; i<lowerString.length;i++) {
charCode.push(lowerString[i].charCodeAt());
}
let newCharCode = charCode.map(x => {
if (x > 96 && x < 123 && this._number > x - 96) {
return 122 - (this._number - (x - 96));
} else if (x > 96 && x < 123) {
return x - this._number;
} else return x;
})
let newString = "";
newCharCode.forEach(x => newString += String.fromCharCode(x))
return console.log(newString);
}
}
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'