재귀 함수

오주형·2023년 1월 27일
0

Recursive

const userA = { name: 'A', parent: null }
const userB = { name: 'B', parent: userA }
const userC = { name: 'C', parent: userB }
const userD = { name: 'D', parent: userC }

const getRootUser = user => {
  if (user.parent) {
    return getRootUser(user.parent)
  }
  return user
}

console.log(getRootUser(userD)); // {name: 'A', parent: null}
console.log(getRootUser(userC)); // {name: 'A', parent: null}
console.log(getRootUser(userB)); // {name: 'A', parent: null}
console.log(getRootUser(userA)); // {name: 'A', parent: null}
profile
곧 개발자

0개의 댓글