# Caesars Cipher: good code practice?

Caesars Cipher: good code practice?
0
#1

I just solved this challenge but I’m not sure about the quality of my code. Is it OK to combine if/else statements with `map()`? And is it OK to chain two map functions together?

Many thanks

Kostas

``````  var newArray = [];

for(var i=0;i<str.length;i++){
newArray.push(str.charCodeAt(i));
}

var result = newArray.map(function(item){
if(item>77){
return item-13;
}else if(item<77 && item>64 || item===77){
return item+13;
}
return item;
}).map(function(item){
return String.fromCharCode(item);
});
return result.join("");

}
// Change the inputs below to test
rot13("LBH QVQ VG!");
``````

Your Browser User Agent is: `Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36`.

https://www.freecodecamp.org/challenges/caesars-cipher

0 Likes

#2

Putting if/else in the function is fine.

One thing jumped off the page at me though: `(item<77 && item>64 || item===77)`. Remember that the operator `<=` exists.

1 Like

#3

Yes

Yes, but why do you feel you need to in this case? Since your 2nd map function just returns the character converted from the item with the following line, why not just reassign the item - 13 or item + 13 to item (instead of returning those values in the first map) and just use this line in the first map instead of the return item; line?

``````return String.fromCharCode(item);
``````

In case you can not figure it out, I have blurred out what I describe below.

``````function rot13(str) {
var newArray = [];
for (var i = 0; i < str.length; i++) {
newArray.push(str.charCodeAt(i));
}
var result = newArray.map(function(item) {
if (item > 77) {
item = item - 13;
} else if ((item < 77 && item > 64) || item === 77) {
item = item + 13;
}
return String.fromCharCode(item);
});
return result.join('');
}
// Change the inputs below to test
rot13('LBH QVQ VG!');
``````
2 Likes