array-treeify
Version:
Simple text tree diagrams from arrays.
56 lines (55 loc) • 2.21 kB
TypeScript
/**
* The strict tree input format. Must start with a string.
* This type is exported for testing purposes and advanced usage.
*/
export type TreeInput = Array<string | TreeInput>;
/**
* Flexible input type that accepts any array.
* Runtime validation ensures the first element is a string.
*/
type FlexibleTreeInput = readonly (string | unknown[])[];
/**
* ASCII characters used to render the tree.
*/
export type TreeChars = {
branch: string;
lastBranch: string;
pipe: string;
space: string;
};
/**
* @description Creates a text tree representation from a nested array structure using Unicode box-drawing characters.
*
* The expected input format is a hierarchical structure where:
* - The first element must be a string (the root node)
* - String elements represent nodes at the current level
* - Array elements following a string represent the children of the previous node
* - Nested arrays create deeper levels in the tree
*
* Examples of supported formats:
* - `['root', ['child1', 'child2', 'child3']]` creates a root with three children
* - `['root', 'second', ['child1', 'child2']]` creates multiple root nodes with children
* - `['root', ['child1', ['grandchild1', 'grandchild2']]]` creates a root with nested children
* - `['root', ['childA', ['grandchildA'], 'childB']]` creates multiple branches
*
* The output uses Unicode box-drawing characters to visualize the tree structure.
*
* @param list {FlexibleTreeInput} - An array representing the tree structure. First element must be a string.
* @param options {Object} - An object containing optional configuration:
* - `chars` {TreeChars} - Custom characters for the tree. Defaults to Unicode box-drawing characters.
* - `plain` {boolean} - Whether to use plain whitespace characters instead of Unicode box-drawing characters.
*
* @returns {string} A string containing the tree representation
*
* @example
* treeify(['root', ['child1', 'child2', ['grandchild']]])
* // root
* // ├─ child1
* // └─ child2
* // └─ grandchild
*/
export declare function treeify(list: FlexibleTreeInput, options?: {
chars?: TreeChars;
plain?: boolean;
}): string;
export {};