Line data Source code
1 : interface PromotedWidgetExpansion<T> {
2 : hasWidget: boolean
3 : nested: readonly T[]
4 : }
5 :
6 51 : export function hasPromotedWidgetTarget<T>(
7 : root: T,
8 : maxDepth: number,
9 : keyOf: (value: T) => unknown,
10 : expand: (value: T) => PromotedWidgetExpansion<T>
11 : ): boolean {
12 51 : const active = new Set<unknown>()
13 51 : const resolved = new Map<unknown, boolean>()
14 :
15 51 : const visit = (
16 : value: T,
17 : depth: number
18 : ): { found: boolean; truncated: boolean } => {
19 51 : const key = keyOf(value)
20 51 : const settled = resolved.get(key)
21 51 : if (settled !== undefined) return { found: settled, truncated: false }
22 51 : if (active.has(key)) return { found: false, truncated: false }
23 51 : active.add(key)
24 :
25 51 : const { hasWidget, nested } = expand(value)
26 51 : let found = hasWidget
27 51 : let truncated = false
28 51 : for (const child of nested) {
29 0 : if (found) break
30 0 : if (depth >= maxDepth) {
31 0 : truncated = true
32 0 : continue
33 : }
34 0 : const result = visit(child, depth + 1)
35 0 : found = result.found
36 0 : truncated ||= result.truncated
37 : }
38 :
39 51 : active.delete(key)
40 51 : if (found || !truncated) resolved.set(key, found)
41 51 : return { found, truncated }
42 : }
43 :
44 51 : return visit(root, 0).found
45 : }
|