[SPOILER ALERT] JavaScript Algorithms and Data Structures Projects: Caesars Cipher

Hi everybody,

I’ve just finished this code and would love to hear your feedback, wheter I overcomplicate things or should do more simple steps for better readibility etc.

Thank you very much for your time

PS: I made it more versatile on top of the challenge.

const ASCII_MIN = 33
const ASCII_MAX = 127

function rot13(str = '',num = 13,start = 65){
    // generate array
    const gen = (arr = []) => {
        return arr = new Array(num).fill(null).map(e => {
            if(start > ASCII_MAX){
                start = ASCII_MIN
            }
            return String.fromCharCode(start++)})
        }
    // populate array   
    const A = gen()
    const B = gen()
    // 1. split into word array, then each word into letters array and map through each letter
    // 2. if letter not found in either of A or B, then don't change it
    // 3. if letter NOT found in A then pick letter from A with index from B and vice versa
    // 4. join back together
    return str = (() =>
        str
        .split(' ')
        .map(word => word
            .split('')
            .map(letter => A.indexOf(letter) < 0 && B.indexOf(letter) < 0 
            ? letter
            : A.indexOf(letter) < 0
            ? A[B.indexOf(letter)]
            : B[A.indexOf(letter)]) 
            .join('')) 
        .join(' ')
    )()
}

Hi there,

great work so far!

Ideas:

  • For me, the naming is hard to understand, e.g. what does ASCII_MIN and ASCII_MAX mean? What does rot13 do? Does it decode stuff? Or encode it? What does the num param mean? What does the gen function generate?
  • Why does the gen function have a default parameter?
  • Why do you use an IIFE for the last return?

Keep us posted!

Keep us posted!

Hi,

thanks a lot for your feedback.

So you’re saying that anything that CANNOT be read directly from the code should be commented? As why do I assign such and such value into global constants and little talking about what upcoming code does etc.

I’ll definetely try developing this good practice.

About the IIFE, do you think it’s better to create a function decleration or function expression and invoke it right after?
I don’t really see why I couldn’t do it this way? Are there any downsides?

I would start giving a more explicit name, e.g. LOWEST_POSSIBLE_ASCII_CODE instead of ASCII_MIN. This is very explicit, but I think not every person knows what an ASCII code is or what MIN stands for. But that’s only my personal thought about this.

I think this:

    return str = (() =>
        str
        .split(' ')
        .map(...) 
        .join(' ')
    )()

is similar to:

    return str
        .split(' ')
        .map(...) 
        .join(' ')
    )

, but with less code.