Reputation: 71
I am trying to create a caesar cypher, I know this might not be the best or easiest way to do it but I created a recursive function that loops over adding numbers to each character in order to change it to a different character, but when I run my code instead of getting a character as an answer I get undefined
'''
const caesar = function(inputString, shiftNo) {
let outputString = "";
for (let i = 0; i < inputString.length; i++){
let unicodeCode = inputString.charCodeAt(i);
if ( unicodeCode <= 90 && unicodeCode >= 65 || unicodeCode <= 122 && unicodeCode >= 97){
outputString += recCounter(unicodeCode, shiftNo);
}
else{
outputString += inputString.charAt(i);
}
}
return outputString;
}
function recCounter(unicodeCode, shiftNo){
let shiftedUniCode = unicodeCode;
let substractedShiftNum = shiftNo;
if (shiftedUniCode === 123){
shiftedUniCode = 97;
}
else if (shiftedUniCode === 91){
shiftedUniCode = 65;
}
if (shiftNo === 0){
return String.fromCharCode(shiftedUniCode);
}
else {
recCounter(shiftedUniCode + 1, substractedShiftNum - 1);
}
}
'''
I have tried changing the parameters and the way the recursive function works but all I get is undefined when I run my code
Upvotes: 0
Views: 63
Reputation: 1435
you skipped the return on the recursive call
change:
recCounter(shiftedUniCode + 1, substractedShiftNum - 1);
to:
return recCounter(shiftedUniCode + 1, substractedShiftNum - 1);
Upvotes: 1