0

I've been preparing for a bootcamp interview so I'm going through the exercise of creating a program that would cypher a string using the ROT13 cypher. For those that are unfamiliar, here's a diagram showing how it works:

ROT13

The issue that I'm facing with my code is that when I iterate through my for-loop, whatever result I get from each iteration wouldn't go through the IF statements despite meeting the conditions. If there are any suggestions to optimize this code, I would also greatly appreciate that!

This is all very new and frustrating but so fun at the same time!

function jCheck(num){
  if (num >= 26){
    return num - 26
  }
  else {
    return num
  }
}

function flipStr(str){
  const upperCheck = /[A-Z]/g
  const lowerCheck =/[a-z]/g
  const upperAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  const lowerAlpha = "abcdefghijklmnopqrstuvwxyz"
  let newStr = []
  for (let i = 0; i < str.length; i++){
    console.log(str[i],lowerCheck.test(str[i]))
    if (lowerCheck.test(str[i]) === true){
      console.log('lower ran')
      let j = lowerAlpha.indexOf(str[i]) + 13
      j = jCheck(j)
      newStr.push(lowerAlpha[j])
    }
    else if (upperCheck.test(str[i]) === true){
      let j = upperAlpha.indexOf(str[i]) + 13
      j = jCheck(j)
      newStr.push(upperAlpha[j])
    }
    else{
      console.log('else ran')
      newStr.push(str[i])
    }
  }
  return newStr.join("")
}

var input = 'aaaaaa!'
console.log(flipStr(input)) // outputs 'nanana!' instead of 'nnnnnn!'
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Jsema
  • 1
  • 1
    You have the global flag `g` in your regexes which makes the execution wrong. Funnily, because you've added the `console.log` which executes the regex *again*, the output is even more wrong. If you just remove the `g` and leave the regex as `/[A-Z]/` and `/[a-z]/` you get the expected result. – VLAZ Jan 10 '20 at 19:26
  • That answered my question. I shouldn't have put the global flag without fully understanding it's functionality. Thanks for that. – Jsema Jan 10 '20 at 19:32

0 Answers0