-
Notifications
You must be signed in to change notification settings - Fork 0
40 Recursion
Biswajit Sundara edited this page Aug 18, 2023
·
1 revision
Recursion is a programming technique in which a function calls itself repeatedly until a certain condition is met.
- This is useful in handling repetitive calculations or processing.
- Recursion is useful when processing data structures such as linked lists and trees.
function factorial(n) {
if (n === 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(3));We can refactor the code as below.
function factorial(n) {
return n === 1 ? 1 : n * factorial(n - 1);
}
console.log(factorial(3));function powerOf(x,n) {
return n === 1 ? x : x * powerOf(x,n - 1);
}
console.log(powerOf(5,2));- Let's say on social media data we are parsing friends list
- I have friends -> they have their own friend list, and some might not have also
- So here we are doing
repetitiveprocessing, it's related tostructureand we don't know the exactcount of iterations - So recursion is preferred over loops.
const myself = {
name: "Biswajit",
friends: [
{
name: "Mark",
friends: [
{
name: "Steve",
friends: [
{
name: "Bob",
},
{
name: "Harry",
},
],
},
],
},
{
name: "Jeane",
},
],
};
function getFriendNames(person) {
const collectedNames = [];
if (!person.friends) {
return [];
}
for (const friend of person.friends) {
collectedNames.push(friend.name);
collectedNames.push(...getFriendNames(friend));
}
return collectedNames;
}
console.log(getFriendNames(myself));