Blame view

src/utils/helper/treeHelper.ts 5.49 KB
陈文彬 authored
1
2
3
4
5
interface TreeHelperConfig {
  id: string;
  children: string;
  pid: string;
}
6
7

// 默认配置
陈文彬 authored
8
9
10
11
12
13
const DEFAULT_CONFIG: TreeHelperConfig = {
  id: 'id',
  children: 'children',
  pid: 'pid',
};
14
// 获取配置。  Object.assign 从一个或多个源对象复制到目标对象
陈文彬 authored
15
16
17
const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config);

// tree from list
18
// 列表中的树
陈文彬 authored
19
20
21
22
23
24
25
26
27
28
29
30
export function listToTree<T = any>(list: any[], config: Partial<TreeHelperConfig> = {}): T[] {
  const conf = getConfig(config) as TreeHelperConfig;
  const nodeMap = new Map();
  const result: T[] = [];
  const { id, children, pid } = conf;

  for (const node of list) {
    node[children] = node[children] || [];
    nodeMap.set(node[id], node);
  }
  for (const node of list) {
    const parent = nodeMap.get(node[pid]);
31
    (parent ? parent[children] : result).push(node);
陈文彬 authored
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  }
  return result;
}

export function treeToList<T = any>(tree: any, config: Partial<TreeHelperConfig> = {}): T {
  config = getConfig(config);
  const { children } = config;
  const result: any = [...tree];
  for (let i = 0; i < result.length; i++) {
    if (!result[i][children!]) continue;
    result.splice(i + 1, 0, ...result[i][children!]);
  }
  return result;
}

export function findNode<T = any>(
  tree: any,
  func: Fn,
vben authored
50
  config: Partial<TreeHelperConfig> = {},
陈文彬 authored
51
52
53
54
55
56
57
58
59
60
61
62
63
64
): T | null {
  config = getConfig(config);
  const { children } = config;
  const list = [...tree];
  for (const node of list) {
    if (func(node)) return node;
    node[children!] && list.push(...node[children!]);
  }
  return null;
}

export function findNodeAll<T = any>(
  tree: any,
  func: Fn,
vben authored
65
  config: Partial<TreeHelperConfig> = {},
陈文彬 authored
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
): T[] {
  config = getConfig(config);
  const { children } = config;
  const list = [...tree];
  const result: T[] = [];
  for (const node of list) {
    func(node) && result.push(node);
    node[children!] && list.push(...node[children!]);
  }
  return result;
}

export function findPath<T = any>(
  tree: any,
  func: Fn,
vben authored
81
  config: Partial<TreeHelperConfig> = {},
陈文彬 authored
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
): T | T[] | null {
  config = getConfig(config);
  const path: T[] = [];
  const list = [...tree];
  const visitedSet = new Set();
  const { children } = config;
  while (list.length) {
    const node = list[0];
    if (visitedSet.has(node)) {
      path.pop();
      list.shift();
    } else {
      visitedSet.add(node);
      node[children!] && list.unshift(...node[children!]);
      path.push(node);
      if (func(node)) {
        return path;
      }
    }
  }
  return null;
}

export function findPathAll(tree: any, func: Fn, config: Partial<TreeHelperConfig> = {}) {
  config = getConfig(config);
107
  const path: any[] = [];
陈文彬 authored
108
  const list = [...tree];
109
  const result: any[] = [];
陈文彬 authored
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
  const visitedSet = new Set(),
    { children } = config;
  while (list.length) {
    const node = list[0];
    if (visitedSet.has(node)) {
      path.pop();
      list.shift();
    } else {
      visitedSet.add(node);
      node[children!] && list.unshift(...node[children!]);
      path.push(node);
      func(node) && result.push([...path]);
    }
  }
  return result;
}

export function filter<T = any>(
  tree: T[],
  func: (n: T) => boolean,
130
  // Partial 将 T 中的所有属性设为可选
vben authored
131
  config: Partial<TreeHelperConfig> = {},
vben authored
132
): T[] {
133
  // 获取配置
陈文彬 authored
134
135
  config = getConfig(config);
  const children = config.children as string;
136
陈文彬 authored
137
138
139
140
  function listFilter(list: T[]) {
    return list
      .map((node: any) => ({ ...node }))
      .filter((node) => {
141
        // 递归调用 对含有children项  进行再次调用自身函数 listFilter
陈文彬 authored
142
        node[children] = node[children] && listFilter(node[children]);
143
        // 执行传入的回调 func 进行过滤
陈文彬 authored
144
145
146
        return func(node) || (node[children] && node[children].length);
      });
  }
147
陈文彬 authored
148
149
150
151
152
153
  return listFilter(tree);
}

export function forEach<T = any>(
  tree: T[],
  func: (n: T) => any,
vben authored
154
  config: Partial<TreeHelperConfig> = {},
vben authored
155
): void {
陈文彬 authored
156
157
158
159
  config = getConfig(config);
  const list: any[] = [...tree];
  const { children } = config;
  for (let i = 0; i < list.length; i++) {
160
161
162
163
    //func 返回true就终止遍历,避免大量节点场景下无意义循环,引起浏览器卡顿
    if (func(list[i])) {
      return;
    }
陈文彬 authored
164
165
166
167
168
    children && list[i][children] && list.splice(i + 1, 0, ...list[i][children]);
  }
}

/**
169
 * @description: Extract tree specified structure
170
 * @description: 提取树指定结构
陈文彬 authored
171
 */
vben authored
172
export function treeMap<T = any>(treeData: T[], opt: { children?: string; conversion: Fn }): T[] {
陈文彬 authored
173
174
  return treeData.map((item) => treeMapEach(item, opt));
}
175
陈文彬 authored
176
/**
177
 * @description: Extract tree specified structure
178
 * @description: 提取树指定结构
陈文彬 authored
179
180
181
 */
export function treeMapEach(
  data: any,
vben authored
182
  { children = 'children', conversion }: { children?: string; conversion: Fn },
陈文彬 authored
183
184
185
186
187
188
189
190
191
192
) {
  const haveChildren = Array.isArray(data[children]) && data[children].length > 0;
  const conversionData = conversion(data) || {};
  if (haveChildren) {
    return {
      ...conversionData,
      [children]: data[children].map((i: number) =>
        treeMapEach(i, {
          children,
          conversion,
vben authored
193
        }),
陈文彬 authored
194
195
196
197
198
199
200
201
      ),
    };
  } else {
    return {
      ...conversionData,
    };
  }
}
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216

/**
 * 递归遍历树结构
 * @param treeDatas 树
 * @param callBack 回调
 * @param parentNode 父节点
 */
export function eachTree(treeDatas: any[], callBack: Fn, parentNode = {}) {
  treeDatas.forEach((element) => {
    const newNode = callBack(element, parentNode) || element;
    if (element.children) {
      eachTree(element.children, callBack, newNode);
    }
  });
}