Skip to content

Instantly share code, notes, and snippets.

@alejo4373
Last active May 18, 2020 01:31
Show Gist options
  • Save alejo4373/bf5e953b6ce66cd28229f2a03eb27d85 to your computer and use it in GitHub Desktop.
Save alejo4373/bf5e953b6ce66cd28229f2a03eb27d85 to your computer and use it in GitHub Desktop.
const countDownFromN = (n) => {
if (n < 0) {
return
}
console.log('up:', n)
countDownFromN(n - 1)
// console.log('do:', n) // This is weird but its due to the call stack. If you understand why this happens, you understand recursion.
}
countDownFromN(10)
// First valid approach. Removing the first element of the array each time
// O(n) Time
// O(n) Space
// iterateRecursive = (arr) => {
// if (arr.length === 0) {
// return
// }
// let arrayCopy = [...arr] // With the spread op really a copy
// console.log(arrayCopy[0])
// arrayCopy.shift()
// iterateRecursive(arrayCopy)
// }
// Another valid approach. Iterates from the back and uses and index to
// O(n) Time
// O(1) Space
iterateRecursive = (arr, index = arr.length - 1) => {
if (index < 0 || index >= arr.length) {
return
}
console.log(arr[index])
iterateRecursive(arr, index - 1)
}
let arr = [1, 2, 3, 4]
iterateRecursive(arr, 3)
// 1
// 2
// 3
// 4
// Accumulating/compounding the results of recursive calls
const addAllNumsToN = (n) => {
if (n === 0) {
return 0
}
let result = n + addAllNumsToN(n - 1)
return result;
}
console.log(addAllNumsToN(5))
// n + (n - 1)
// 5 + 4 => 9
// 9 + 3 => 12
// 12 + 2 => 14
// 14 + 1 => 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment