ShiftCipher solution

Here’s my ShiftCipher code. It passed! Was wondering if anyone was able to come up with a simpler solution.

// Write class below

class ShiftCipher {
constructor(shift) {
this._shift = shift;
}

encrypt(message) {
message = message.toUpperCase();
let encodedMessage = ‘’;
for (let i = 0; i < message.length; i++) {
if ((message.charAt(i) >= ‘A’) && (message.charAt(i) <= ‘Z’)) {
encodedMessage = ‘’.concat(encodedMessage, String.fromCharCode(((message.charCodeAt(i) + this._shift - 65) % 26) + 65));
} else {
encodedMessage = ‘’.concat(encodedMessage, message.charAt(i));
}
};
return encodedMessage;
}

decrypt(message) {
message = message.toLowerCase();
let decodedMessage = ‘’;
for (let i = 0; i < message.length; i++) {
if ((message.charAt(i) >= ‘a’) && (message.charAt(i) <= ‘z’)) {
decodedMessage = ‘’.concat(decodedMessage, String.fromCharCode(((message.charCodeAt(i) - this._shift - 122) % 26) + 122));
} else {
decodedMessage = ‘’.concat(decodedMessage, message.charAt(i));
}
}
return decodedMessage;
}

}

  • This is your same code but with javascript ternary operator shorthand.
  • ternary shorthand can be used on if, else, and return.
  • check and see if the code below produces the result you want. A test message or the entire code would help me to check.
  • The code below passes though I’m not sure it gives the result you want so be sure to check it or just get a general idea from it.
  • Its your still your code refactored btw. I don’t have a copy of this exercise or remember where it was.
  • I also threw in regex for checking A to Z with /[A-Z]/
  • Oh sometimes you need for i in something instead of for i of something so test or look up the differences and see which one you need and when. I get them confused also.
class ShiftCipher {
    constructor(shift) {
        this._shift = shift;
    };

    encrypt(message) {
        message = message.toUpperCase();
        let encodedMessage = '';
        for (let i of message) {
            return ( i in /[A-Z]/ ) ? encodedMessage =  ''.concat(encodedMessage, String.fromCharCode(((i + this._shift - 65) % 26) + 65))
            : encodedMessage = ''.concat(encodedMessage, i );
        };
    };

    decrypt(message) {
        message = message.toLowerCase();
        let decodedMessage = '';
        for (let i of message) {
            return ( i in /[a-z]/ ) ? decodedMessage = ''.concat(decodedMessage, String.fromCharCode(((i - this._shift - 122) % 26) + 122))
            : decodedMessage = ''.concat(decodedMessage, i );
        };
    };
}

looking at it one last time I removed message.charAt(i) and just used i as it is which now holds the character itself.
Do it which ever way works best for you.

1 Like

In my code, i is an index. In yours, i is a character in the string. Also, i in /[a-z]/ doesn’t work, but i.match(/[a-z]/ does.

1 Like

noted thanks :grin:
I’m keeping this in my files for future reference.