Skip to content

Commit 22b7c41

Browse files
committed
refactor: children methods tree
1 parent ea11c62 commit 22b7c41

File tree

2 files changed

+28
-15
lines changed

2 files changed

+28
-15
lines changed

src/codegen/generateRouteMap.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ export function generateRouteRecordInfo(node: TreeNode) {
2828
]
2929

3030
if (node.children.size > 0) {
31-
const deepNamedChildren = node
32-
.getChildrenDeep()
31+
// TODO: remove Array.from() once Node 20 support is dropped
32+
const deepNamedChildren = Array.from(node.getChildrenDeep())
3333
// skip routes that are not added to the types
3434
.filter(
3535
(childRoute) => childRoute.value.components.size > 0 && childRoute.name

src/core/tree.ts

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -130,23 +130,36 @@ export class TreeNode {
130130
this.value.setOverride(filePath, routeBlock)
131131
}
132132

133-
getSortedChildren(): TreeNode[] {
134-
return Array.from(this.children.values()).sort((a, b) =>
135-
a.path.localeCompare(b.path)
136-
)
133+
/**
134+
* Generator that yields all descendants without sorting.
135+
* Use with Array.from() for now, native .map() support in Node 22+.
136+
*/
137+
*getChildrenDeep(): Generator<TreeNode> {
138+
for (const child of this.children.values()) {
139+
yield child
140+
yield* child.getChildrenDeep()
141+
}
142+
}
143+
144+
/**
145+
* Comparator function for sorting TreeNodes by path.
146+
*/
147+
static compareByPath(a: TreeNode, b: TreeNode): number {
148+
return a.path.localeCompare(b.path)
137149
}
138150

139-
getSortedChildrenDeep(): TreeNode[] {
140-
return Array.from(this.children.values())
141-
.flatMap((child) => [child, ...child.getSortedChildrenDeep()])
142-
.sort((a, b) => a.path.localeCompare(b.path))
151+
/**
152+
* Get the children of this node sorted by their path.
153+
*/
154+
getSortedChildren(): TreeNode[] {
155+
return Array.from(this.children.values()).sort(TreeNode.compareByPath)
143156
}
144157

145-
getChildrenDeep(): TreeNode[] {
146-
return Array.from(this.children.values()).flatMap((child) => [
147-
child,
148-
...child.getChildrenDeep(),
149-
])
158+
/**
159+
* Calls {@link getChildrenDeep} and sorts the result by path in the end.
160+
*/
161+
getChildrenDeepSorted(): TreeNode[] {
162+
return Array.from(this.getChildrenDeep()).sort(TreeNode.compareByPath)
150163
}
151164

152165
/**

0 commit comments

Comments
 (0)