Рекурсия — это в основном процесс или функция, которая вызывает саму себя, но с другим меньшим вводом. Рекурсию можно найти в различных методах JavaScript, таких как JSON.parse(), алгоритмы обхода DOM JSON.stringify и других.

Есть две основные части рекурсивной функции:

  1. Базовый случай, который является концом строки, где функция останавливается,
  2. Другой ввод каждый раз, когда функция вызывает себя.

Некоторые проблемы с рекурсией и их решения:

  1. NestedEvenSum. Напишите рекурсивную функцию с именем nestedEvenSum. Возвращает сумму всех четных чисел в объекте, который может содержать вложенные объекты. Функция будет принимать образцы ввода, такие как:

Решение:

// result is initialized to 0 by default.
function nestedEvenSum(obj, result = 0) {
// base case if the object is empty
if(Object.keys(obj).length === 0) return result;
// iterating through each key in the obj parameter
  for (const key in obj) {
/* If the value of the current key in obj is an object,
the function calls itself recursively, 
passing in the object as the new obj parameter. 
The value returned from the recursive call is then added to the result.
*/   
if (typeof obj[key] === "object") {
      result += nestedEvenSum(obj[key]);
    }
/*If the value of the current key in obj is a number and is even,
 the value is added to the result.
*/
    if (typeof obj[key] === 'number' && obj[key] % 2 === 0) {
      result += obj[key];
    }
  }
// The returned value is the sum of all the even numbers.
  return result;
}

2. Reverse: напишите рекурсивную функцию с именем reverse, которая принимает строку и возвращает новую строку в обратном порядке.

function reverse(str){
// initialize result to the last character of the input string str
  let result = str.charAt(str.length-1);
// base case to return result is str length is zero
  if(str.length === 0) return result;
/* reverse is recursively called with a substring of str that excludes the last 
character.
the result of this call is concatenated with result
*/
  result = result.concat(reverse(str.slice(0,str.length-1)))
  return result;
}

3. CapitalizeFirst: напишите рекурсивную функцию с именем capitalizeFirst. Учитывая массив строк, сделайте заглавной первую букву каждой строки в массиве.

function capitalizeFirst(oldArr) {
    let newArr = [];
// base case
    if (oldArr.length === 0) return newArr;
// capitalize the first character of the string and concatenates it with the rest of the string, and pushes the new string to the newArr.
    newArr.push(oldArr[0].charAt(0).toUpperCase() + oldArr[0].slice(1));
// the function is called recursively with a slice of oldArr that excludes the first element
    newArr = newArr.concat(capitalizeFirst(oldArr.slice(1)))
    return newArr;
}

Вот некоторые решения сложных проблем рекурсии в JavaScript. Рекурсия может быть мощным инструментом, но она также может привести к таким проблемам, как переполнение стека, если ее использовать неправильно. Важно помнить о базовом случае и следить за тем, чтобы функция приближалась к базовому случаю с каждым рекурсивным вызовом.