Skip to content

Instantly share code, notes, and snippets.

@jonurry
Last active April 28, 2021 03:01
Show Gist options
  • Select an option

  • Save jonurry/95ce2b5e98a2c9cfb44b13da37aa2105 to your computer and use it in GitHub Desktop.

Select an option

Save jonurry/95ce2b5e98a2c9cfb44b13da37aa2105 to your computer and use it in GitHub Desktop.
3.2 Recursion (Eloquent JavaScript Solutions)
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));
// → ??
@jonurry
Copy link
Copy Markdown
Author

jonurry commented Feb 16, 2018

Hints

Your function will likely look somewhat similar to the inner find function in the recursive findSolution example in this chapter, with an if/else if/else chain that tests which of the three cases applies. The final else, corresponding to the third case, makes the recursive call. Each of the branches should contain a return statement 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.

@Angstromico
Copy link
Copy Markdown

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment