0

I am trying to write a function to solve caeser cipher. I have already written the program in python and the answer I got seemed right. But when I tried to convert the algorithm to javascript, the value returned by the function always has "undefined" in the end(despite adding a return command to the function). I have looked through similar problems listed in stack overflow, but none seemed to match my own. Any help will be greatly appreciated. Thanks in advance.

const 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"];
function rot13(str) {
    var ans = ""
    for (let i=0; i<=str.length; i++){
        if (alphabet.includes(str[i])){
        if (alphabet.indexOf(str[i])<alphabet.length/2){
            ans += alphabet[alphabet.indexOf(str[i]) + 13]
        } else{
            ans += alphabet[13 - (alphabet.length - alphabet.indexOf(str[i]))]}
        } else{
            ans += str[i]
        }
    }
    return ans
}
  • `i<=str.length` is almost always an off-by-one in a loop condition. PS: you never really seem to algorithmically use the index, a `for ... of` would be simpler (although not technically exactly identical for surrogate pairs etc) – ASDFGerte Dec 25 '21 at 19:23
  • Thanks a lot! That post you tagged fixed it for me. – AsafUllah Dec 26 '21 at 05:45

0 Answers0