| 1234567891011121314151617181920212223242526272829303132333435 |
- import XEUtils from "xe-utils";
- declare type TreeSearch<D> = {
- children?: D[],
- $visible?: boolean
- } & D
- export const treeSearch = <D = any>(data: D[], iterator: (item: TreeSearch<D>) => boolean): D[] => {
- data = XEUtils.clone(data, true);
- function filterDataByVisible(tempData: D[]): D[] {
- return XEUtils.filter(tempData, (item: TreeSearch<D>): boolean => {
- if (item.children) {
- item.children = filterDataByVisible(item.children);
- }
- return !!item.$visible;
- })
- }
- const traverse = (tempData: D[]): void => {
- XEUtils.arrayEach(tempData, (child: TreeSearch<D>): void => {
- child.$visible = iterator(child);
- if (child.children) {
- traverse(child.children);
- }
- if (!child.$visible && child.children?.length) {
- const $visible: boolean = !child.children.some((child) => child.$visible);
- child.$visible = !$visible;
- }
- })
- };
- traverse(data);
- return filterDataByVisible(data);
- }
|