Skip to content

Instantly share code, notes, and snippets.

@TehShrike
Last active July 25, 2026 13:24
Show Gist options
  • Select an option

  • Save TehShrike/0844919e8dcc1dbdeea508e4d7052e04 to your computer and use it in GitHub Desktop.

Select an option

Save TehShrike/0844919e8dcc1dbdeea508e4d7052e04 to your computer and use it in GitHub Desktop.
Recursion
// 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)
}
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