-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9bce687
commit 913bc2d
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
// Prompt | ||
// Write a function "reverseString" that takes a string as input, and returns that string reversed. You MUST use recursion for your answer. Any form of looping (including built-ins like .forEach) are forbidden for your solution. | ||
|
||
// hello | ||
// ello | ||
// llo | ||
// lo | ||
// o | ||
// '' | ||
// '' | ||
|
||
const reverseString = (inputString) => { | ||
console.log('Going Down: ', inputString); | ||
|
||
// Base Case - Where do we stop calling ourselves again? | ||
if (inputString.length === 0) { | ||
return ''; | ||
} | ||
// Recursive Case - When do we call ourselves again? | ||
const restOfCharactersReversed = reverseString(inputString.substring(1, inputString.length)); | ||
console.log('Result of Reversal While Coming Up: ', restOfCharactersReversed); | ||
|
||
// Return - How do we create the value over time? | ||
return restOfCharactersReversed + inputString[0]; | ||
} | ||
|
||
console.log(reverseString('hello')); // => olleh | ||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
// Solution | ||
// const reverseString = (inputString) => { | ||
// // Base Case: Return nothing if there are no characters left. | ||
// if (inputString.length === 0) { | ||
// return ''; | ||
// } | ||
// | ||
// // Recursive Case: Reverse every character in the string besides for the first one. | ||
// const restOfStringReversed = reverseString( | ||
// inputString.substring(1, inputString.length), | ||
// ); | ||
// | ||
// // Because, we will append whatever the "first" character was at this level to the end of the rest of the string reversed. | ||
// return restOfStringReversed + inputString.charAt(0); | ||
// }; | ||
// | ||
// console.log(reverseString('hello')); // => olleh |