xxxxxxxxxx
// Lets create a basic recursion
// num parameter set to 1 as default
function recursion(num = 1) {
// when num is greater than 10 return (break)
if (num > 10) return
console.log(num)
// if num is not greater than 10 call the function again but add 1 to num
recursion(num + 1)
}
// logs 1 to 10
recursion()
// now lets take this to another level
// lets create a Fibonacci Sequence
function fib(num, arr = [0, 1]) {
// if num is less than 2 return array
if (num < 2) return arr;
// else
// take the second to last and last item of array with 'destructuring'
// we take second to last item with .slice(-2) but getting the item next to it
// with destructuring
// look it up when I saw this first time my mind blown
const [secondToLast, last] = arr.slice(-2);
// now if num is not less than 2
// lets return the same function that we are inside of
// and set to num to a minus of itsef
// then we will use spread operator "..."
// this means our array's items are now part of another array
// in other words we spread the items of arr to another array
// then lets grab the secondToLast and last variables and put it inside of new array
// so in second loop it will look like simply this
// lets say in the first loop we passed number is 8
// num will be a minus of itself
// so we will reach another step to "2" break
// array will be itself plus the secondToLast + last
// the second loop will represent
// fib(7, [0, 1, 2]) - because 0 + 1 is 2
// and third loop will look like this
// fib(6, [0, 1, 2, 3]) - because 1 + 2 is 3
// until the num is less than 2
// and if it's less than two
// we get our array
return fib(num - 1, [arr, secondToLast + last])
}
console.log(
fib(8) // logs [0,1,1,2,3,5,8,13,21]
)
xxxxxxxxxx
function sum(n) {
if (n === 0) return n;
return n + sum(n - 1);
};
xxxxxxxxxx
/*
Recursion is when a function calls itself until someone stops it.
If no one stops it then it'll recurse (call itself) forever.
*/
// program to count down numbers to 1
function countDown(number) {
// display the number
console.log(number);
// decrease the number value
const newNumber = number - 1;
// base case
if (newNumber > 0) {
countDown(newNumber);
}
}
countDown(4);
// Out put:
4
3
2
1
xxxxxxxxxx
function plus(n) {
if (n === 0) {
return 1; // Base case: return 1 when n is 0
} else {
return plus(n - 1) + 1; // Recursively call plus with n-1 and add 1
}
}
console.log(plus(4)); // Output: 5
xxxxxxxxxx
function walkTree(node) {
if (node == null) //
return;
// do something with node
for (var i = 0; i < node.childNodes.length; i++) {
walkTree(node.childNodes[i]);
}
}