treeHelper.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. interface TreeHelperConfig {
  2. id: string;
  3. children: string;
  4. pid: string;
  5. }
  6. // 默认配置
  7. const DEFAULT_CONFIG: TreeHelperConfig = {
  8. id: 'id',
  9. children: 'children',
  10. pid: 'pid',
  11. };
  12. // 获取配置。 Object.assign 从一个或多个源对象复制到目标对象
  13. const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config);
  14. // tree from list
  15. // 列表中的树
  16. export function listToTree<T = any>(list: any[], config: Partial<TreeHelperConfig> = {}): T[] {
  17. const conf = getConfig(config) as TreeHelperConfig;
  18. const nodeMap = new Map();
  19. const result: T[] = [];
  20. const { id, children, pid } = conf;
  21. for (const node of list) {
  22. node[children] = node[children] || [];
  23. nodeMap.set(node[id], node);
  24. }
  25. for (const node of list) {
  26. const parent = nodeMap.get(node[pid]);
  27. (parent ? parent[children] : result).push(node);
  28. }
  29. return result;
  30. }
  31. export function treeToList<T = any>(tree: any, config: Partial<TreeHelperConfig> = {}): T {
  32. config = getConfig(config);
  33. const { children } = config;
  34. const result: any = [...tree];
  35. for (let i = 0; i < result.length; i++) {
  36. if (!result[i][children!]) continue;
  37. result.splice(i + 1, 0, ...result[i][children!]);
  38. }
  39. return result;
  40. }
  41. export function findNode<T = any>(tree: any, func: Fn, config: Partial<TreeHelperConfig> = {}): T | null {
  42. config = getConfig(config);
  43. const { children } = config;
  44. const list = [...tree];
  45. for (const node of list) {
  46. if (func(node)) return node;
  47. node[children!] && list.push(...node[children!]);
  48. }
  49. return null;
  50. }
  51. export function findNodeAll<T = any>(tree: any, func: Fn, config: Partial<TreeHelperConfig> = {}): T[] {
  52. config = getConfig(config);
  53. const { children } = config;
  54. const list = [...tree];
  55. const result: T[] = [];
  56. for (const node of list) {
  57. func(node) && result.push(node);
  58. node[children!] && list.push(...node[children!]);
  59. }
  60. return result;
  61. }
  62. export function findPath<T = any>(tree: any, func: Fn, config: Partial<TreeHelperConfig> = {}): T | T[] | null {
  63. config = getConfig(config);
  64. const path: T[] = [];
  65. const list = [...tree];
  66. const visitedSet = new Set();
  67. const { children } = config;
  68. while (list.length) {
  69. const node = list[0];
  70. if (visitedSet.has(node)) {
  71. path.pop();
  72. list.shift();
  73. } else {
  74. visitedSet.add(node);
  75. node[children!] && list.unshift(...node[children!]);
  76. path.push(node);
  77. if (func(node)) {
  78. return path;
  79. }
  80. }
  81. }
  82. return null;
  83. }
  84. export function findPathAll(tree: any, func: Fn, config: Partial<TreeHelperConfig> = {}) {
  85. config = getConfig(config);
  86. const path: any[] = [];
  87. const list = [...tree];
  88. const result: any[] = [];
  89. const visitedSet = new Set(),
  90. { children } = config;
  91. while (list.length) {
  92. const node = list[0];
  93. if (visitedSet.has(node)) {
  94. path.pop();
  95. list.shift();
  96. } else {
  97. visitedSet.add(node);
  98. node[children!] && list.unshift(...node[children!]);
  99. path.push(node);
  100. func(node) && result.push([...path]);
  101. }
  102. }
  103. return result;
  104. }
  105. export function filter<T = any>(
  106. tree: T[],
  107. func: (n: T) => boolean,
  108. // Partial 将 T 中的所有属性设为可选
  109. config: Partial<TreeHelperConfig> = {}
  110. ): T[] {
  111. // 获取配置
  112. config = getConfig(config);
  113. const children = config.children as string;
  114. function listFilter(list: T[]) {
  115. return list
  116. .map((node: any) => ({ ...node }))
  117. .filter((node) => {
  118. // 递归调用 对含有children项 进行再次调用自身函数 listFilter
  119. node[children] = node[children] && listFilter(node[children]);
  120. // 执行传入的回调 func 进行过滤
  121. return func(node) || (node[children] && node[children].length);
  122. });
  123. }
  124. return listFilter(tree);
  125. }
  126. export function forEach<T = any>(tree: T[], func: (n: T) => any, config: Partial<TreeHelperConfig> = {}): void {
  127. config = getConfig(config);
  128. const list: any[] = [...tree];
  129. const { children } = config;
  130. for (let i = 0; i < list.length; i++) {
  131. //func 返回true就终止遍历,避免大量节点场景下无意义循环,引起浏览器卡顿
  132. if (func(list[i])) {
  133. return;
  134. }
  135. children && list[i][children] && list.splice(i + 1, 0, ...list[i][children]);
  136. }
  137. }
  138. /**
  139. * @description: Extract tree specified structure
  140. * @description: 提取树指定结构
  141. */
  142. export function treeMap<T = any>(treeData: T[], opt: { children?: string; conversion: Fn }): T[] {
  143. return treeData.map((item) => treeMapEach(item, opt));
  144. }
  145. /**
  146. * @description: Extract tree specified structure
  147. * @description: 提取树指定结构
  148. */
  149. export function treeMapEach(data: any, { children = 'children', conversion }: { children?: string; conversion: Fn }) {
  150. const haveChildren = Array.isArray(data[children]) && data[children].length > 0;
  151. const conversionData = conversion(data) || {};
  152. if (haveChildren) {
  153. return {
  154. ...conversionData,
  155. [children]: data[children].map((i: number) =>
  156. treeMapEach(i, {
  157. children,
  158. conversion,
  159. })
  160. ),
  161. };
  162. } else {
  163. return {
  164. ...conversionData,
  165. };
  166. }
  167. }
  168. /**
  169. * 递归遍历树结构
  170. * @param treeDatas 树
  171. * @param callBack 回调
  172. * @param parentNode 父节点
  173. */
  174. export function eachTree(treeDatas: any[], callBack: Fn, parentNode = {}) {
  175. treeDatas.forEach((element) => {
  176. const newNode = callBack(element, parentNode) || element;
  177. if (element.children) {
  178. eachTree(element.children, callBack, newNode);
  179. }
  180. });
  181. }