Skip to content

Instantly share code, notes, and snippets.

@dgowrie
Last active September 7, 2019 05:04
Show Gist options
  • Save dgowrie/76d05b12af2d3d77d1502761b0927f23 to your computer and use it in GitHub Desktop.
Save dgowrie/76d05b12af2d3d77d1502761b0927f23 to your computer and use it in GitHub Desktop.
Simple example of recursion - web dev interview, discussion
// e.g. "write a simple function that logs out the factor of a given number"
// input '4' should return '24' since 4 * 3 * 2 * 1 = 24
// input '6' should return '720' etc...
// First, discuss and consider the basic utility of a `while` loop
function factor(number) {
let result = 1;
let count = number;
while (count > 1) {
result *= count;
count--;
}
return result;
}
console.log('should be 24', factor(4));
console.log('should be 720', factor(6));
// alternatively just ask for a countdown function
function countdownLoop(value) {
while (value > 0) {
console.log(value--);
}
return value;
}
console.log(countdownLoop(10));
// discuss some downsides to a loop...
// - state that's being maintained / changed in that function
// ... how can we reproduce the functionality of a while loop without creating all that state
// recursion countdown
// - discuss terminal condition
function countdownRecursively(value) {
if (value > 0) {
console.log(value);
return countdownRecursively(value - 1);
} else {
return value;
}
}
const terminal = countdownRecursively(10);
console.log(terminal);
// Now the recursive function for getting a factorial
function factorial(number) {
if (number <= 0) {
return 1;
} else {
return (number * factorial(number - 1));
}
}
console.log(factorial(6));
// discussion points, value of using recursive functions is clean code that you get.
// We're performing a stateless operation.
// We're not changing the value of any variables along the way.
// We're having no side effects outside of the functions, so nothing outside is being changed.
// We're testing for the terminal condition first. And that allows us to
// exit quickly and cleanly from our recursive function.
// downsides of recursion
// - high memory usage of deep recursion
// - code difficult to read for those unfamiliar with recursion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment