0

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

4
  • 6
    The recursive call needs a return. Commented Feb 10, 2020 at 20:00
  • @pointy there already is a return when the variable "shiftNo" equals zero Commented Feb 10, 2020 at 20:02
  • 1
    In the else clause, it should be: return recCounter(...). Without that return statement, your function returns undefined, not the result of your recursive call. Commented Feb 10, 2020 at 20:05
  • @Rios A function only returns to its callee, one step. The return is then not use, aka dead code, and there is always an invisible line saying return undefined; in all functions so when you don't return anything JS does. Commented Feb 10, 2020 at 20:10

1 Answer 1

1

you skipped the return on the recursive call
change:

recCounter(shiftedUniCode + 1, substractedShiftNum - 1);

to:

 return recCounter(shiftedUniCode + 1, substractedShiftNum - 1);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.