1

I am working on an algorithm and i need some help. Here s the problem:

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.

And here is my code

function rot13(str) {
  let letters = ['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"];
  let newStr = str.toLowerCase()

  for(let i = 0; i < newStr.length; i++){
    if(letters.indexOf(newStr[i]) > 13){
      newStr.replace(newStr[i], letters[letters.indexOf(newStr[i]) - 13])
    } else {
      newStr.replace(newStr[i], letters[letters.indexOf(newStr[i]) + 13])
    }
  }
  return newStr.toUpperCase();
}

console.log(rot13("SERR PBQR PNZC"));

I saw that after it replaces one letter the newStr returns to it original form and the nothing is changed. What is the problem?

Robert
  • 23
  • 3

2 Answers2

0

The replace command does not replace the data in the provided string, but returns a string where the substitution is made. To update newStr you need

newStr = newStr.replace(...)
Lala5th
  • 1,137
  • 7
  • 18
0

The previous answer is correct (the replace function returns a string, doesn't perform an update on the original input).

You can also use the map function of an array (which can work on a string, which acts as an array of characters).

function rot13(str, shiftAmt = 13) {
  const alphabetSize = 26
  const ord = character => character.charCodeAt(0)
  const baseOrd = ord("A")
  const index = character => ord(character) - baseOrd
  const char = charCode => String.fromCharCode(charCode)
  const shifted = character => char((index(character) + shiftAmt) % alphabetSize + baseOrd)

  const resultArr = Array.prototype.map.call(str.toUpperCase(), chr => chr >= "A" && chr <= "Z" ? shifted(chr) : chr)
  
  return resultArr.join("")
}
console.log(rot13("SERR PBQR PNZC"));

Result:

FREE CODE CAMP
ELinda
  • 2,658
  • 1
  • 10
  • 9