Tell us what’s happening:
Is this code unsavable? I have an array of the decoded cipher already, but to get that
I removed everything that Isn’t a letter from the string and now I can’t add them back (for example, white spaces and punctuation)
Your code so far
function rot13(str) {
let nArr = []
const letters = (() => {
const caps = [...Array(26)].map((val, i) => String. fromCharCode(i + 65));
return caps.concat();})();
let strS = str.replace(/\s/g, "")
for (let l of strS){
let x = strS.charCodeAt(strS.indexOf(l))
for (let lt of letters){
if (lt == l){
let lIndex = letters.indexOf(l)
nArr.push(letters[lIndex - 13])
if (letters[lIndex - 13] == undefined){
nArr.push(letters[lIndex + 13])
}
}
}
}
nArr.map((x) => {
if (x === undefined){
nArr.splice(nArr.indexOf(undefined), 1)
}
})
console.log(nArr)
return str;
}
rot13("SERR PBQR PNZC");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0.
also I need to point out that this is an anti-pattern - map returns a new array, you loose it like that
why don’t you use filter there? which also returns an array but with less items
Can you help me on replacing the characters? I figured out a way how to only work with the letters of the alphabet but now I can’t figure out how to replace them
function rot13(str) {
let nStr = str
const 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'
]
for (let l of nStr){
if (letters.includes(l)){
let lIndex = letters.indexOf(l)
//console.log(letters[lIndex - 13])
var x = nStr.replace(l, letters[lIndex - 13])
}
}
console.log(x)
return str;
}
rot13("SERR PBQR PNZC");
I’ve been coding in one form or another since 1983. And each time i do the Caesar cipher, i do it differently - and each time, it takes days.
It will take you as long as it takes. If someone whose does it quicker, then they have had a different experience than yours… But yours is no less valid.
The last time i did the cipher, it was learning about functional programming, so the concepts were both advanced and completely different to me. It took a long while, i think four days, but i learned much more than simply writing a cipher.
You’re learning about how to parse and modify strings with non-alphabetic characters in place, you’re being introduced to the idea of anti-patterns, you’re brain is growing by leaps and bounds!