1+ /**
2+ * Recursively finds the most suitable parent entry for a given `entry` based on heading depth.
3+ *
4+ * @param {ApiDocMetadataEntry } entry
5+ * @param {ApiDocMetadataEntry[] } entry
6+ * @param {number } startIdx
7+ * @returns {import('../types.d.ts').HierarchizedEntry }
8+ */
9+ function findParent ( entry , entries , startIdx ) {
10+ // Base case: if we're at the beginning of the list, no valid parent exists.
11+ if ( startIdx < 0 ) {
12+ throw new Error (
13+ `Cannot find a suitable parent for entry at index ${ startIdx + 1 } `
14+ ) ;
15+ }
16+
17+ const candidateParent = entries [ startIdx ] ;
18+ const candidateDepth = candidateParent . heading . depth ;
19+
20+ // If we find a suitable parent, return it.
21+ if ( candidateDepth < entry . heading . depth ) {
22+ candidateParent . hierarchyChildren ??= [ ] ;
23+ return candidateParent ;
24+ }
25+
26+ // Recurse upwards to find a suitable parent.
27+ return findParent ( entry , entries , startIdx - 1 ) ;
28+ }
29+
130/**
231 * We need the files to be in a hierarchy based off of depth, but they're
332 * given to us flattened. So, let's fix that.
2049export function buildHierarchy ( entries ) {
2150 const roots = [ ] ;
2251
23- // Recursive helper to find the parent with a depth less than the current depth.
24- function findParent ( entry , startIdx ) {
25- // Base case: if we're at the beginning of the list, no valid parent exists.
26- if ( startIdx < 0 ) {
27- throw new Error (
28- `Cannot find a suitable parent for entry at index ${ startIdx + 1 } `
29- ) ;
30- }
31-
32- const candidateParent = entries [ startIdx ] ;
33- const candidateDepth = candidateParent . heading . depth ;
34-
35- // If we find a suitable parent, return it.
36- if ( candidateDepth < entry . heading . depth ) {
37- candidateParent . hierarchyChildren ??= [ ] ;
38- return candidateParent ;
39- }
40-
41- // Recurse upwards to find a suitable parent.
42- return findParent ( entry , startIdx - 1 ) ;
43- }
44-
4552 // Main loop to construct the hierarchy.
4653 for ( let i = 0 ; i < entries . length ; i ++ ) {
4754 const entry = entries [ i ] ;
@@ -62,7 +69,7 @@ export function buildHierarchy(entries) {
6269 previousEntry . hierarchyChildren . push ( entry ) ;
6370 } else {
6471 // Use recursive helper to find the nearest valid parent.
65- const parent = findParent ( entry , i - 2 ) ;
72+ const parent = findParent ( entry , entries , i - 2 ) ;
6673 parent . hierarchyChildren . push ( entry ) ;
6774 }
6875 }
0 commit comments