Recursion Advance Problems - rohit120582sharma/Documentation GitHub Wiki
Write a recursive function called reverse which accepts a string and returns a new string in reverse.
// Write a recursive function called Reverse which accepts a string and returns a new string in reverse.
function reverse(str){
// Declare variables
var length = str.length;
// Base Case
if(length <= 1) return str;
// Change input and return
var lastChar = str.charAt(length-1);
var subStr = str.substr(0, (length - 1));
// return
return lastChar + reverse(subStr);
}
// reverse('awesome') // 'emosewa'
// reverse('rithmschool') // 'loohcsmhtir'
Write a recursive function called isPalindrome which returns true if the string passed to it is a palindrome (reads the same forward and backward). Otherwise it returns false.
function isPalindrome(str){
// Base case
if(str.length <= 1) return true;
if(str.length <= 2) return (str[0] === str[1]);
// Change input and return
if(str[0] === str.slice(-1)){
return isPalindrome(str.slice(1,-1));
}
return false;
}
// isPalindrome('awesome') // false
// isPalindrome('foobar') // false
// isPalindrome('tacocat') // true
// isPalindrome('amanaplanacanalpanama') // true
// isPalindrome('amanaplanacanalpandemonium') // false
Write a recursive function called flatten which accepts an array of arrays and returns a new array with all values flattened.
function flatten(oldArr){
// Create an return array
var newArr = [];
// Loop over an array
for(var i=0; i<oldArr.length; i++){
if(Array.isArray(oldArr[i])){
newArr = newArr.concat(flatten(oldArr[i]));
}else{
newArr.push(oldArr[i]);
}
}
// Return
return newArr;
}