-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecursion.js
85 lines (66 loc) · 1.57 KB
/
recursion.js
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
// sum of elements in array in recursion
function sumOfArray(array){
if(array.length===0){
return 0
}
return array[0]+sumOfArray(array.slice(1))
}
console.log(sumOfArray([3,5,2,6,5,7]));
// palindrome usign recursion
function palindromeString(str){
if(str.length<=1){
return true
}
if(str.charAt(0) !== str.charAt(str.length-1)){
return false
}
return isPalindrome(str.slice(1,-1))
}
console.log(palindromeString('hola'));
// factorial recursion
function factorial(value){
if(value===1){
return value
}
return value * factorial(value-1)
}
console.log(factorial(5));
// fibanocci recursion
function fibanocci(value){
if(value<2){
return value
}
return fibanocci(value-1)+fibanocci(value-2)
}
console.log(fibanocci(5));
// string reverse
function reverseString(str){
if(str===''){
return ''
}else{
console.log(reverseString(str.substr(1))+str.charAt(0));
return reverseString(str.substr(1))+str.charAt(0)
}
}
console.log(reverseString('welcome'));
// this is another method for reverse string
function reverseString(str){
if(str===''){
return ''
}
return str.charAt(-1)+reverseString(str.slice(0,-1))
}
console.log();
// this is another method for reverse string
function reverseString(str){
if(str===''){
return ''
}
return str.slice(-1)+reverseString(str.slice(0,-1))
}
const str='racecar'
if(str===reverseString(str)){
console.log('palindrome');
}else{
console.log('not ');
}