array-utils.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import XEUtils from "xe-utils";
  2. declare type TreeSearch<D> = {
  3. children?: D[],
  4. $visible?: boolean
  5. } & D
  6. export const treeSearch = <D = any>(data: D[], iterator: (item: TreeSearch<D>) => boolean): D[] => {
  7. data = XEUtils.clone(data, true);
  8. function filterDataByVisible(tempData: D[]): D[] {
  9. return XEUtils.filter(tempData, (item: TreeSearch<D>): boolean => {
  10. if (item.children) {
  11. item.children = filterDataByVisible(item.children);
  12. }
  13. return !!item.$visible;
  14. })
  15. }
  16. const traverse = (tempData: D[]): void => {
  17. XEUtils.arrayEach(tempData, (child: TreeSearch<D>): void => {
  18. child.$visible = iterator(child);
  19. if (child.children) {
  20. traverse(child.children);
  21. }
  22. if (!child.$visible && child.children?.length) {
  23. const $visible: boolean = !child.children.some((child) => child.$visible);
  24. child.$visible = !$visible;
  25. }
  26. })
  27. };
  28. traverse(data);
  29. return filterDataByVisible(data);
  30. }