Skip to content

Commit

Permalink
fixup! fixup! fixup! fixup! fixup! feat(json): add legacy JSON generator
Browse files Browse the repository at this point in the history
  • Loading branch information
avivkeller committed Nov 12, 2024
1 parent 5b448fe commit 2e2f3f0
Show file tree
Hide file tree
Showing 2 changed files with 211 additions and 250 deletions.
53 changes: 30 additions & 23 deletions src/generators/legacy-json/utils/buildHierarchy.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
/**
* Recursively finds the most suitable parent entry for a given `entry` based on heading depth.
*
* @param {ApiDocMetadataEntry} entry
* @param {ApiDocMetadataEntry[]} entry
* @param {number} startIdx
* @returns {import('../types.d.ts').HierarchizedEntry}
*/
function findParent(entry, entries, startIdx) {
// Base case: if we're at the beginning of the list, no valid parent exists.
if (startIdx < 0) {
throw new Error(
`Cannot find a suitable parent for entry at index ${startIdx + 1}`
);
}

const candidateParent = entries[startIdx];
const candidateDepth = candidateParent.heading.depth;

// If we find a suitable parent, return it.
if (candidateDepth < entry.heading.depth) {
candidateParent.hierarchyChildren ??= [];
return candidateParent;
}

// Recurse upwards to find a suitable parent.
return findParent(entry, entries, startIdx - 1);
}

/**
* We need the files to be in a hierarchy based off of depth, but they're
* given to us flattened. So, let's fix that.
Expand All @@ -20,28 +49,6 @@
export function buildHierarchy(entries) {
const roots = [];

// Recursive helper to find the parent with a depth less than the current depth.
function findParent(entry, startIdx) {
// Base case: if we're at the beginning of the list, no valid parent exists.
if (startIdx < 0) {
throw new Error(
`Cannot find a suitable parent for entry at index ${startIdx + 1}`
);
}

const candidateParent = entries[startIdx];
const candidateDepth = candidateParent.heading.depth;

// If we find a suitable parent, return it.
if (candidateDepth < entry.heading.depth) {
candidateParent.hierarchyChildren ??= [];
return candidateParent;
}

// Recurse upwards to find a suitable parent.
return findParent(entry, startIdx - 1);
}

// Main loop to construct the hierarchy.
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
Expand All @@ -62,7 +69,7 @@ export function buildHierarchy(entries) {
previousEntry.hierarchyChildren.push(entry);
} else {
// Use recursive helper to find the nearest valid parent.
const parent = findParent(entry, i - 2);
const parent = findParent(entry, entries, i - 2);
parent.hierarchyChildren.push(entry);
}
}
Expand Down
Loading

0 comments on commit 2e2f3f0

Please sign in to comment.