JS) 재귀함수

ynnsuis·2023년 7월 11일
0

x를 n번 제곱하는 함수를 만들때 재귀함수를 사용할 수 있다.
재귀함수는 다음과 같은 형태인데,

function powerOf(x,n){
  if(n === 1){
    return;
  }
  
  retun x * powerOf(x,n-1)
}

함수 안에 동일한 함수가 무한 중첩되는 형태로써, n이 1씩 줄어들어 break point인 n이 1되는 지점까지 해당 함수를 무한 반복한다.
powerOf(2,3); 를 실행해보면 8이라는 올바른 답을 얻을 수 있다.

다른 사용 예로는

 const post = {
    title: "title",
    description: "description",
    comments: [
      {
        text: "comment1",
        comments: [
          {
            text: "comment1-1",
            comments: [
              {
                text: "comment1-1-1",
              },
              {
                text: "comment1-1-2",
              },
            ],
          },
          {
            text: "comment1-1",
            comments: [
              {
                text: "comment1-2-1",
              },
              {
                text: "comment1-2-2",
              },
            ],
          },
        ],
      },
      {
        text: "comment2",
      },
    ],
  };
        

이런식으로 객체가 알수없는 만큼 복잡하게 중첩되어 있는 객체에서 데이터를 읽을때도 유용하게 사용할 수 있다.

  function getComments(post) {
    const collectedComments = [];

    if (!post.comments) {
      return [];
    }

    for (const comment of post.comments) {
      collectedComments.push(comment.text);
      collectedComments.push(...getComments(comment));
    }

    return collectedComments;
  }

  console.log(getComments(post));

이런식으로 재귀함수를 작성하면 끝이 어딘지 모를정도로 복잡한 중첩객체에서 comments들의 text 값만 빼와서 배열에 담는게 가능하다.

0개의 댓글