All files / src tree-formatter.ts

100% Statements 16/16
94.11% Branches 16/17
100% Functions 2/2
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49          2x               7x     7x 4x     7x 7x 8x 8x 8x 8x   8x   8x 3x         7x                   2x      
import { TreeNode } from './types'
 
/**
 * Utility class for formatting tree structures
 */
export class TreeFormatter {
  /**
   * Converts tree structure to a readable string representation
   * @param node The tree node to convert
   * @param indent Current indentation level
   * @returns String representation of the tree
   */
  static treeToString(node: TreeNode, indent: string = ''): string {
    let result = ''
    
    // Only add the root node name if we're at the top level
    if (indent === '') {
      result = `${node.name}${node.type === 'directory' ? '/' : ''}\n`
    }
    
    if (node.children) {
      for (let i = 0; i < node.children.length; i++) {
        const child = node.children[i]
        const isLast = i === node.children.length - 1
        const childIndent = indent + (isLast ? '└── ' : '├── ')
        const nextIndent = indent + (isLast ? '    ' : '│   ')
        
        result += `${childIndent}${child.name}${child.type === 'directory' ? '/' : ''}\n`
        
        if (child.children && child.children.length > 0) {
          result += this.treeToString(child, nextIndent)
        }
      }
    }
    
    return result
  }
 
  /**
   * Converts tree structure to JSON string
   * @param node The tree node to convert
   * @param pretty Whether to format the JSON with indentation
   * @returns JSON string representation of the tree
   */
  static treeToJson(node: TreeNode, pretty: boolean = true): string {
    return JSON.stringify(node, null, pretty ? 2 : 0)
  }
}