12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- interface TreeConfigOptions {
-
- childProps: string;
- }
- function traverseTreeValues<T, V>(
- tree: T[],
- getValue: (node: T) => V,
- options?: TreeConfigOptions,
- ): V[] {
- const result: V[] = [];
- const { childProps } = options || {
- childProps: 'children',
- };
- const dfs = (treeNode: T) => {
- const value = getValue(treeNode);
- result.push(value);
- const children = (treeNode as Record<string, any>)?.[childProps];
- if (!children) {
- return;
- }
- if (children.length > 0) {
- for (const child of children) {
- dfs(child);
- }
- }
- };
- for (const treeNode of tree) {
- dfs(treeNode);
- }
- return result.filter(Boolean);
- }
- function filterTree<T extends Record<string, any>>(
- tree: T[],
- filter: (node: T) => boolean,
- options?: TreeConfigOptions,
- ): T[] {
- const { childProps } = options || {
- childProps: 'children',
- };
- const _filterTree = (nodes: T[]): T[] => {
- return nodes.filter((node: Record<string, any>) => {
- if (filter(node as T)) {
- if (node[childProps]) {
- node[childProps] = _filterTree(node[childProps]);
- }
- return true;
- }
- return false;
- });
- };
- return _filterTree(tree);
- }
- function mapTree<T, V extends Record<string, any>>(
- tree: T[],
- mapper: (node: T) => V,
- options?: TreeConfigOptions,
- ): V[] {
- const { childProps } = options || {
- childProps: 'children',
- };
- return tree.map((node) => {
- const mapperNode: Record<string, any> = mapper(node);
- if (mapperNode[childProps]) {
- mapperNode[childProps] = mapTree(mapperNode[childProps], mapper, options);
- }
- return mapperNode as V;
- });
- }
- export { filterTree, mapTree, traverseTreeValues };
|