My solution Caesars Cipher

Continuing the discussion from freeCodeCamp Challenge Guide: Caesars Cipher:

Here’s my solution to the Caesars cipher challenge; my question is, is any of the proposed solutions in the challenge better performance wise than mine? because it didn’t seem that way at first glance. then again, i’m a begginer =)

function rot13(str) {
  let decoded = "";
  let alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
  for(let i=0;i<str.length;i++) {
    if(str[i].match(/\W/)) {
      decoded += str[i];
    }
    alphabet.forEach(elem => {if(str[i] === elem && alphabet.indexOf(str[i])-13 >= 0) {
      decoded += alphabet[alphabet.indexOf(str[i])-13];
    }
    else if(str[i] === elem && alphabet.indexOf(str[i])-13 < 0) {
      decoded += alphabet[alphabet.indexOf(str[i])+13];
    };
    });
  }
  return decoded;
}

You’re doing a lot of searching the alphabet array, which is slow. Using the character codes directly is much faster.

3 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.