forked from ant-design/ant-design
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.tsx
80 lines (75 loc) · 1.98 KB
/
util.tsx
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import * as React from 'react';
import { ColumnFilterItem } from './interface';
export function flatArray(data: any[] = [], childrenName = 'children') {
const result: any[] = [];
const loop = (array: any[]) => {
array.forEach(item => {
if (item[childrenName]) {
const newItem = { ...item };
delete newItem[childrenName];
result.push(newItem);
if (item[childrenName].length > 0) {
loop(item[childrenName]);
}
} else {
result.push(item);
}
});
};
loop(data);
return result;
}
export function treeMap<Node>(
tree: Node[],
mapper: (node: Node, index: number) => any,
childrenName = 'children',
) {
return tree.map((node: any, index) => {
const extra: any = {};
if (node[childrenName]) {
extra[childrenName] = treeMap(node[childrenName], mapper, childrenName);
}
return {
...mapper(node as Node, index),
...extra,
};
});
}
export function flatFilter(tree: any[], callback: Function) {
return tree.reduce((acc, node) => {
if (callback(node)) {
acc.push(node);
}
if (node.children) {
const children = flatFilter(node.children, callback);
acc.push(...children);
}
return acc;
}, []);
}
export function normalizeColumns(elements: React.ReactChildren) {
const columns: any[] = [];
React.Children.forEach(elements, element => {
if (!React.isValidElement(element)) {
return;
}
const column: any = {
...element.props,
};
if (element.key) {
column.key = element.key;
}
if (element.type && (element.type as any).__ANT_TABLE_COLUMN_GROUP) {
column.children = normalizeColumns(column.children);
}
columns.push(column);
});
return columns;
}
export function generateValueMaps(items?: ColumnFilterItem[], maps: { [name: string]: any } = {}) {
(items || []).forEach(({ value, children }) => {
maps[value.toString()] = value;
generateValueMaps(children, maps);
});
return maps;
}