Caesar's Cipher Algorithm (JS Algorithm & Data Structures Project)

Please review my Caesar’s Cipher algorithm and offer your feedback.

View code on Github or below. Thank you in advance.

/**
 * One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. 
 * In a shift cipher the meanings of the letters are shifted by some set amount.
 * 
 * A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places.
 * Thus A ↔ N, B ↔ O and so on.
 * 
 * Write a function which takes a ROT13 encoded string as input and returns a decoded string.
 * 
 * All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.
 */
function rot13(str) {
    let lettersA2M = "ABCDEFGHIJKLM";
    let lettersN2Z = "NOPQRSTUVWXYZ";
    let decodedString = "";
    for (let i = 0; i < str.length; i++) {
        if (str[i].match(/[A-M]/)) {
            decodedString += lettersN2Z[lettersA2M.indexOf(str[i])];
        } else if (str[i].match(/[N-Z]/)) {
            decodedString += lettersA2M[lettersN2Z.indexOf(str[i])];
        } else {
            decodedString += str[i];
        }
    }
    return decodedString;
}

Interesting approach, seems logical. Does it pass? At this stage, it’s more a question of “finding your way over the mountain” than being all pretty while doing it.

There are many valid ways to tackle the Caesar challenge, and this is one.

2 Likes

(post deleted by author)