(obj: TreeNode, options: TreeifyOptions = {})
| 37 | * Based on https://github.com/notatestuser/treeify |
| 38 | */ |
| 39 | export function treeify(obj: TreeNode, options: TreeifyOptions = {}): string { |
| 40 | const { |
| 41 | showValues = true, |
| 42 | hideFunctions = false, |
| 43 | themeName = 'dark', |
| 44 | treeCharColors = {}, |
| 45 | } = options |
| 46 | |
| 47 | const lines: string[] = [] |
| 48 | const visited = new WeakSet<object>() |
| 49 | |
| 50 | function colorize(text: string, colorKey?: keyof Theme): string { |
| 51 | if (!colorKey) return text |
| 52 | return color(colorKey, themeName)(text) |
| 53 | } |
| 54 | |
| 55 | function growBranch( |
| 56 | node: TreeNode | string, |
| 57 | prefix: string, |
| 58 | _isLast: boolean, |
| 59 | depth: number = 0, |
| 60 | ): void { |
| 61 | if (typeof node === 'string') { |
| 62 | lines.push(prefix + colorize(node, treeCharColors.value)) |
| 63 | return |
| 64 | } |
| 65 | |
| 66 | if (typeof node !== 'object' || node === null) { |
| 67 | if (showValues) { |
| 68 | const valueStr = String(node) |
| 69 | lines.push(prefix + colorize(valueStr, treeCharColors.value)) |
| 70 | } |
| 71 | return |
| 72 | } |
| 73 | |
| 74 | // Check for circular references |
| 75 | if (visited.has(node)) { |
| 76 | lines.push(prefix + colorize('[Circular]', treeCharColors.value)) |
| 77 | return |
| 78 | } |
| 79 | visited.add(node) |
| 80 | |
| 81 | const keys = Object.keys(node).filter(key => { |
| 82 | const value = node[key] |
| 83 | if (hideFunctions && typeof value === 'function') return false |
| 84 | return true |
| 85 | }) |
| 86 | |
| 87 | keys.forEach((key, index) => { |
| 88 | const value = node[key] |
| 89 | const isLastKey = index === keys.length - 1 |
| 90 | const nodePrefix = depth === 0 && index === 0 ? '' : prefix |
| 91 | |
| 92 | // Determine which tree character to use |
| 93 | const treeChar = isLastKey |
| 94 | ? DEFAULT_TREE_CHARS.lastBranch |
| 95 | : DEFAULT_TREE_CHARS.branch |
| 96 | const coloredTreeChar = colorize(treeChar, treeCharColors.treeChar) |
no test coverage detected