The challenge: Given a string S and a fixed number K, rotate every letter in S by K places (if reach the end of the alphabet, go back to the beginning). Letters should remain the same case. Symbols should remain unencrypted.
Constraints: K is between 0 and 100. S is a valid ASCII string without spaces, between 1 and 100 letters long.
Input: The first line contains an integer, N , which is the length of the unencrypted string. The second line contains the unencrypted string, S. The third line contains the integer encryption key, K, which is the number of letters to rotate.
I'd appreciate any comments and suggestions as to how my code can be improved.
var lowerString = "abcdefghijklmnopqrstuvwxyz";
var lower = lowerString.split("");
var upperString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var upper = upperString.split("");
function main() {
var n = parseInt(readLine());
var s = readLine();
var k = parseInt(readLine());
printCipher(s, k);
}
function printCipher(str, key){
var newStr = "";
str.split("").forEach(function(elem, index){
var changedItem = cipher(elem, key);
newStr += changedItem;
});
console.log(newStr);
}
function cipher(item, key){
var arrToUse = null;
if(lower.indexOf(item) >= 0){
arrToUse = lower;
}
else if (upper.indexOf(item) >= 0){
arrToUse = upper;
}
if(arrToUse !== null){
var pos = arrToUse.indexOf(item);
var newPos = getCipherPosition(pos, key);
return arrToUse[newPos];
}
return item;
}
function getCipherPosition(pos, key){
const ALPHA_COUNT = 26;
if(key > ALPHA_COUNT){
key = key % ALPHA_COUNT;
}
if(pos + key >= ALPHA_COUNT){
return key + pos - ALPHA_COUNT;
}
return key + pos;
}