Reverse a word, one letter at a time
Turning cat into tac by hand, you would not shuffle the middle. You would
take the last letter, put it first, and do the same thing to ca. Then a goes
in front of c. The word is shrinking by one and the task never changes.
Eating a word one letter at a time is the picture: bite off a letter and you are still looking at a shorter word to finish. The self-similar step is to take one character off the string and attach it to the reverse of what remains.
The base case is the string you cannot shorten past: the empty string. The
reverse of '' is '', and a single character reverses to itself too. Name
that case first.
Shrink the input on every call by one character, so the base case is always
reachable. Then trust the recursive call — assume reverseString(text.slice(1))
already returns the reverse of the rest — and combine: this character goes on the
end.
function reverseString(text) {
if (text.length <= 1) {
return text;
}
return reverseString(text.slice(1)) + text[0];
}
Each call removes a character, so a string of length n unwinds in n steps.
Export reverseString from index.js. It returns a string's characters in
reverse order, and the empty string stays empty.
Challenge
Read backwards, a word is its last letter followed by the reverse of the word
without it — the same task on something shorter. Export a reverseString
function from index.js that reverses a string one character at a time.
reverseString takes a string and returns its characters in reverse order. The
empty string stays empty, and a single character stays itself.