Created
December 24, 2025 21:47
-
-
Save coffeejoshua/a31686ef4617b11d48c892e165c9fed2 to your computer and use it in GitHub Desktop.
My opinion on recursion vs while (in general)
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
| #!/usr/bin/env node | |
| // 0 is even, 1 is odd, and N is even if N-2 is even | |
| /* | |
| Which one is easier to read and understand for you? (Subjectively) | |
| Which one is significantly safer (aka, what could go wrong)? (Objectively) | |
| I found 4 scenarios that would crash the less safe one where the safer one | |
| will return "undefined". Did I miss any? | |
| */ | |
| const recursiveIsEven = function(num) { | |
| // Convert negative numbers to positive | |
| if (num < 0) { | |
| num = -num; | |
| } | |
| if (num == 0) { | |
| return "Even"; | |
| } | |
| if (num == 1) { | |
| return "Odd"; | |
| } | |
| return recursiveIsEven(num - 2); | |
| }; | |
| const whileIsEven = function(num) { | |
| // Convert negative numbers to positive | |
| if (num < 0) { | |
| num = -num; | |
| } | |
| while (num >= 0) { | |
| if (num == 0) { | |
| return "Even"; | |
| } | |
| if (num == 1) { | |
| return "Odd"; | |
| } | |
| num = num -2; | |
| } | |
| }; | |
| console.log(recursiveIsEven(9)); | |
| console.log(recursiveIsEven(-14)); | |
| console.log(whileIsEven(9)); | |
| console.log(whileIsEven(-14)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment