forked from Yadro/time-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeModelHelper.ts
More file actions
77 lines (69 loc) · 1.88 KB
/
TreeModelHelper.ts
File metadata and controls
77 lines (69 loc) · 1.88 KB
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
import { ITreeItem } from '../types/ITreeItem';
const TreeModelHelper = {
modifyItemsWithIdsRecursive<T extends ITreeItem<any>>(
treeItems: T[],
ids: string[],
fn: (treeItem: T, ids: string[]) => void
) {
treeItems.forEach((item) => {
fn(item, ids);
if (Array.isArray(item.children) && item.children.length) {
TreeModelHelper.modifyItemsWithIdsRecursive(item.children, ids, fn);
}
});
},
getItemRecursive<T extends ITreeItem<any>>(
tasks: T[],
condition: (task: T) => boolean
): T | undefined {
for (const task of tasks) {
if (condition(task)) {
return task;
}
if (Array.isArray(task.children)) {
const found = this.getItemRecursive(task.children, condition);
if (found) {
return found;
}
}
}
return undefined;
},
getFlatItemsRecursive<T extends ITreeItem<any>>(
tree: T[],
condition: (task: T) => boolean
): T[] {
const result: T[] = [];
this.getFlatItemsRecursiveBase(tree, condition, result);
return result;
},
getFlatItemsRecursiveBase<T extends ITreeItem<any>>(
treeItems: T[],
condition: (item: T) => boolean,
result: T[]
): T[] {
for (const item of treeItems) {
if (condition(item)) {
result.push(item);
}
if (Array.isArray(item.children)) {
this.getFlatItemsRecursiveBase(item.children, condition, result);
}
}
return result;
},
deleteItems<T extends ITreeItem<any>>(
treeItems: T[],
condition: (task: T) => boolean
): T[] {
const result = treeItems.filter((t) => !condition(t));
for (let i = 0; i < result.length; i++) {
const task = treeItems[i];
if (Array.isArray(task.children)) {
treeItems[i].children = this.deleteItems(task.children, condition);
}
}
return result;
},
};
export default TreeModelHelper;