/** * 将列表数据转换为树形数据 (迭代方式) * 1. 首先创建一个 map 对象,用于通过 id 快速查找节点。 * 2. 遍历列表,将每个节点添加到 map 中,并初始化 children 数组。 * 3. 再次遍历列表,将每个节点添加到其父节点的 children 数组中。 * 4. 最后返回根节点数组。 * * 复杂度分析: * 1. 时间复杂度:O(n),其中 n 是列表的长度。 * 2. 空间复杂度:O(n),其中 n 是列表的长度。 */ type ListItem = { [key: string]: any; }; type Options = { /** * 节点标识字段 * @default "id" */ idKey?: string; /** * 父节点标识字段 * @default "parentId" */ parentKey?: string; /** * 子节点字段 * @default "children" */ childrenKey?: K; /** * 转换节点函数, 默认copy当前节点 * @default (item) => ({ ...item }); * @param item 当前节点 * @returns */ transform?: (item: T) => R; /** * 判断是否为根节点 * @default (item) => !item.parentId * @param item 当前节点 * @returns */ isRoot?: (item: T) => boolean; }; type TreeNode = R & { [P in K]: TreeNode[]; }; /** * Converts a flat list of items into a hierarchical tree structure. * @param list List data * @param options Options * @returns tree data */ declare function listToTree(list: T[], options?: Options): TreeNode[]; export { listToTree as default };