martincartledge.github.io

recursion

a process (a function) that calls itself

commonly used in:

the call stack
writing a recursive function
function countDown(num) {
  if (num <= 0) {
    console.log("all done");
    return;
  }
  console.log(num);
  num--;
  countDown(num);
}

// countDown(3)
// print 3
// countDown(2)
// print 2
// countDown(1)
// print 1
// countDown(0)
// all done
function sumRange(num) {
  if (num === 1) return 1;
  return num + sumRange(num - 1);
}

// sumRange(3) // returns 6
// return 3 + sumRange(2) (returns 3)
// return 2 + sumRange(1) (returns 1)
// return 1
factorial iteratively
function factorial(num) {
  let total = 1;
  for (let i = 0; i > 1; i--) {
    total *= i;
  }
  return total;
}
factorial recursively
function factorial(num) {
  if (num === 1) return 1;
  return num * factorial(num - 1);
}
common recursion pitfalls
helper method recursion
function collectOdds(arr) {
  let result = [];

  function helper(helperInput) {
    if (helperInput.length === 0) return;

    if (helperInput[0] % 2 !== 0) {
      result.push(helperInput[0]);
    }
    helper(helperInput.slice(1));
  }

  helper(arr);

  return result;
}
pure recursion
function collectOdds(arr) {
  let newArr = [];

  if (arr.length === 0) return newArr;

  if (arr[0] % 2 !== 0) {
    newArr.push(arr[0]);
  }

  newArr = newArr.concat(collectOdds(arr.slice(1)));

  return newArr;
}
// collectOdds([1,2,3,4,5])
// [1].concat(collectOdds([2,3,4,5]))
//// [].concat(collectOdds([3,4,5]))
////// [3].concat(collectOdds(4,5))
//////// [].concat(collectOdds([5]))
////////// [5].concat(collectOdds([]))
//////////// []