The aim of this puzzle: Complete the recursive updateAllNames
function.
Walkthrough of the solution: The updateAllNames
function definition isn’t correct. It only replaces the 1st typo which is the same thing the regular .replace()
method does. We need to make the function replace all the typos (spelling errors).
The 1st part of the function is an If Statement that checks if the string
does not include any typos. This is the same as asking if all the typos are gone. If there are no typos, then we should just return
the string
because all the work is done. If that check fails, then we still have typos to fix.
The next line does a .replace()
to fix the first typo it finds. Now our string
is a little better off, because it has 1 less typo. But there may still be typos left. We should do something to check if we’re done or if there are any more typos to fix. Amazingly, we have a function that already checks if the string
is free of typos otherwise it fixes 1 typo – the updateAllNames
function that we’re looking at!
After we did our .replace()
we should call the updateAllNames()
function and return
that value: return updateAllNames(string, oldPart, newPart);
This almost like a loop, because when we run updateAllNames()
the very 1st time, it will probably ask itself to run again, and again. But the important part is that each time the function is called, there is a check right away to see if the work is done. That’s called a “base case”, this is the case that we don’t need to recurse (make the function call itself) anymore.
Also, every time we recurse, we’re getting closer to the base case (no typos), because we’re removing 1 typo every time. Eventually, we will get rid of all the typos and the recursion is complete.
Sample code solution:
(Tap below to reveal)
function updateAllNames(string, oldPart, newPart) {
if (string.includes(oldPart) === false) {
return string;
}
string = string.replace(oldPart, newPart);
return updateAllNames(string, oldPart, newPart);
}
console.log(travelDocument);
console.log(updateAllNames(travelDocument, 'grasshoper', 'grasshopper'));
JavaScript Concepts: Code Block (function, if statement), console.log()
, Recursion, .replace()
Additional Code (hidden code that runs before the puzzle’s code):
let travelDocument =
`Hello grasshoper${pickRandom(['','Travel','Passport','Ticket','Plans','Vacation','Holiday','Trip'])}!
You will be going to ${pickRandom(['New Zealand','Cyprus','the Maldives','Oahu','Palawan','Bali','Maui'])}.
Your travel code is: "${pickRandom(['grasshoper8ugs','im1grasshoper','no1grasshoper'])}"
Enjoy your trip grasshoper!`;