Last active
April 28, 2021 03:01
-
-
Save jonurry/95ce2b5e98a2c9cfb44b13da37aa2105 to your computer and use it in GitHub Desktop.
3.2 Recursion (Eloquent JavaScript Solutions)
This file contains hidden or 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
| function isEven(num) { | |
| if (num == 0) | |
| return true; | |
| if (num == 1) | |
| return false; | |
| if (num < 0) | |
| return "??"; | |
| else return isEven(num - 2); | |
| } | |
| console.log(isEven(50)); | |
| // → true | |
| console.log(isEven(75)); | |
| // → false | |
| console.log(isEven(-1)); | |
| // → ?? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hints
Your function will likely look somewhat similar to the inner
findfunction in the recursivefindSolutionexample in this chapter, with anif/elseif/elsechain that tests which of the three cases applies. The finalelse, corresponding to the third case, makes the recursive call. Each of the branches should contain areturnstatement or in some other way arrange for a specific value to be returned.When given a negative number, the function will recurse again and again, passing itself an ever more negative number, thus getting further and further away from returning a result. It will eventually run out of stack space and abort.