Last active
July 25, 2026 13:24
-
-
Save TehShrike/0844919e8dcc1dbdeea508e4d7052e04 to your computer and use it in GitHub Desktop.
Recursion
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
| // In a world where the only way to find the largest value is to compare 2 at a time | |
| const get_largest_of_two = (a: number, b: number) => { | |
| if (a > b) { | |
| return a | |
| } | |
| return b | |
| } | |
| const find_max_of_many_iterative = (numbers: number[]): number => { | |
| let largest_so_far = -Infinity | |
| numbers.forEach(number => { | |
| largest_so_far = get_largest_of_two(largest_so_far, number) | |
| }) | |
| return largest_so_far | |
| } | |
| const find_max_of_many_recursive = (numbers: number[]): number => { | |
| if (numbers.length === 0) { | |
| return -Infinity | |
| } | |
| const [ first, ...rest ] = numbers | |
| const largest_of_rest = find_max_of_many_recursive(rest) | |
| return get_largest_of_two(first, largest_of_rest) | |
| } |
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
| const numbers = [1,6,1,999,3,2,0,-100] | |
| console.log(find_max_of_many_iterative(numbers)) | |
| console.log(find_max_of_many_recursive(numbers)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment