Skip to content

Instantly share code, notes, and snippets.

@LearningNerd
Created June 5, 2018 19:25
Show Gist options
  • Save LearningNerd/311ff984274792a4beab1b4a0f1fe919 to your computer and use it in GitHub Desktop.
Save LearningNerd/311ff984274792a4beab1b4a0f1fe919 to your computer and use it in GitHub Desktop.
Quick review of recursive functions (2018-06-04)
// Playing with recursion a bit for review
/*
what is there to know about it? lol. hmm
- need a base case, when to STOP recursing!
- function calling itself
- good for recursive structures like trees
- question: what does the call stack look like? how to visualize it?
-- the tricky part is seeing how each call resolves;
-- ....can't show that with console.log :(
*/
/////////////////////////////////////////////////////////////////
// Useless example: recursion to increment a number up to 10
/////////////////////////////////////////////////////////////////
function addToSelf(num) {
console.log("Called addToSelf(" + num + ")");
if (num >= 10) {
return num;
}
return addToSelf(num+1);
}
let result = addToSelf(5);
console.log(result);
// // Alternate version...
// // Exploring: how is this different from recursion? How's it the same?
// function addToSelf(num) {
// console.log("Called addToSelf(" + num + ")");
// return num + 1;
// }
// let result = addToSelf( addToSelf( addToSelf(1) ) );
// console.log(result);
/////////////////////////////////////////////////////////////////
// Factorials (5! === 5 + 4 + 3 + 2 + 1 === 15)
/////////////////////////////////////////////////////////////////
// // Iterative way:
// function loopFactorial(num) {
// let sum = 0;
// for (let i = num; i > 0; i--) {
// sum += i;
// console.log("i: " + i + ", sum: " + sum);
// }
// return sum;
// }
// let sum = loopFactorial(5);
// console.log(sum);
// Recursive way:
function recurseFactorial(factorialNum, partialSum) {
console.log("called recurseFactorial(" + factorialNum + ", " + partialSum + ")");
if (factorialNum == undefined || factorialNum < 0) {
//throw new Error("One positive number is required to call recurseFactorial.");
console.log("One positive number is required to call recurseFactorial.");
return;
// if function is first called with 1 or 0, return 1 or 0
// * assuming user will only ever call the function wiht one argument!
} else if (partialSum == undefined && factorialNum <= 1) { // 0! = 0, and 1! = 1
return factorialNum;
}
// Default value for partial sum: start at 0;
if (partialSum == undefined) {
partialSum = 0;
}
if (factorialNum === 1) {
// NOTE: always decrement 1 at a time, guaranteed for the num to equal 1 at some point, right?
return partialSum + 1;
}
//partialSum += factorialNum;
return recurseFactorial( factorialNum - 1, partialSum + factorialNum);
}
console.log( recurseFactorial(5) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment