After just 2 weeks of coding, I'm struggling to find information on how to initialize a variable with an extra argument in a recursive function call. Is this even possible? And if it is, are there any scenarios where it's considered best practice?
This question arose while I was working on a less-than-elegant solution to CoderByte challenge number 10 (Alphabet Soup - a challenge that involves taking a string and returning a string with the same letters in alphabetical order). [Note: I understand that my approach may not be the best way to solve the problem. I'm including the code only for context.]
In essence, I'm wondering if there's a way to remove 'newStr' as an argument (given that JavaScript functions can take extra arguments) and still pass a recursively growing answer string. If I simply eliminate 'newStr' as an argument, the initialization is lost. However, if I initialize 'newString' within the function body (var newStr = ""), I encounter issues passing the sorted string recursively. Is there a valid use case for this approach, or does it simply signify that another method should be used?
Full Code:
function AlphabetSoup(str, newStr) {
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var testVal= 0;
//ATTEMPTING TO PASS A GROWING ANSWER STRING RECURSIVELY
if (newStr == null)
var newStr = "";
if (str.length == 0)
return newStr;
for (var i = 1; i < str.length; i++) {
if (alphabet.indexOf(str[0]) <= alphabet.indexOf(str[i])) {
testVal += 1;
}
}
// When the first letter, str[0], is earlier in the alphabet than every other letter
if (testVal == (str.length - 1)) {
//add the first letter to the newStr
newStr = newStr + str[0];
//remove the first letter from the input string
str = str.substr(1);
//recursively call AlphabetSoup to continue building newStr
return AlphabetSoup(str, newStr);
}
//When the first letter isn't the earliest in the alphabet
else {
//move it to the end of str
str = str.substr(1) + str[0];
//until we find the next earliest letter in the alphabet
return AlphabetSoup(str, newStr);
}
}
console.log(AlphabetSoup("hooplah"));