본문 바로가기
front/기타

[자바스크립트] 계층형 객체 깊이 구하기

by juniKang 2022. 5. 12.

데이터 구조


interface Data { 
  value: any; 
  children?: Array<Data>; 
}

const data: Data[] = [ 
	{   
      value:"A" 
      cildren:[ 
        { 
          value:"a" 
          children:[ 
            { 
              value:"가" 
            }, 
            { 
              value:"나" 
            }, 
            { 
              value:"다" 
            }, 
          ] 
        }, 
      ] 
    } 
  ]

계산식

 

function calcDepth(options: Data[]) : number{ 
  const depthest = Math.max(...arrDepth(options), 0); 
  return depthest; 
 
  function arrDepth(options: Data[]) : number[]{ 
    const result: number[] = []; 
    aDepth(0, options, result); 
    return result; 
  } 
  function aDepth(d: number, array: Data[], result: number[]) { 
    d++; 
    result.push(d); 
    for (let i = 0; i < array.length; i++) { 
      const e = array[i]; 
      if (e.children) { 
        aDepth(d, e.children, result); 
      } 
    } 
  } 
}​

'front > 기타' 카테고리의 다른 글

[rollup.js]Introduction  (0) 2022.07.27
인터페이스 개발  (0) 2022.07.22
비폭력대화 NVC  (0) 2022.05.16
[The Basics] Types for Tooling  (0) 2022.05.13
[The Basics] Static type-checking  (0) 2022.05.11

댓글