-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursion.js
More file actions
103 lines (80 loc) · 2.26 KB
/
Copy pathrecursion.js
File metadata and controls
103 lines (80 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Recursion is defined as the process of a function calling itself. A recursive function is the function that corresponds to this.
* The base case (or halting condition) and the recursive call to itself are commonly two elements of a recursive function.
* The base case is when the function should no longer'recurse.'
* A recursive call is when a function calls itself, usually with slightly modified arguments that 'work down' to the base case.
*/
// function test() {
// test();
// }
// test();
/**Here test() will call for infinite times as there is no break condition inside the function test. */
/**Base Case: The base case is what stops the recursion from continuing on forever.It act like a terminating condition. */
// General Countdown function
function countdown(n) {
for (let i = n; i > 0; i--) {
console.log(i);
}
}
countdown(3); /**
3
2
1
*/
// recursion function for countdown. Note: We have to write the exit condition first and then the inner function call.
function recursivecountDown(n) {
if (n == 0) // exit condition
return;
console.log(n);
recursivecountDown(n - 1); // function call within function
}
recursivecountDown(3);
function calculateTotal(n) {
let total = 0;
for (let i = 0; i <= n; i++) {
total += i;
}
return total;
}
console.log(calculateTotal(4)); //10
function calculateRecursiveTotal(n, total = 0) {
if (n === 0)
return total;
return calculateRecursiveTotal(n - 1, total += n);
}
console.log(calculateRecursiveTotal(4)); //10
// Using javascript objects
const teamStructure = {
name: 'Kunal',
teams: [
{
name: 'Harish',
teams: [
{
name: 'Alisha',
teams: [
{
name: 'Yash',
teams: []
}
]
},
]
},
{
name: 'Anurag',
teams: []
}
]
}
function getTeamDetail(t) {
// base case
if (t.teams.length === 0) {
return t;
}
t.teams.forEach(team => {
console.log(team.name);
getTeamDetail(team);
});
}
getTeamDetail(teamStructure);