-
Notifications
You must be signed in to change notification settings - Fork 1
/
tree-leafs.ts
33 lines (31 loc) · 940 Bytes
/
tree-leafs.ts
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
import { Observable, concat, of } from 'rxjs';
import { mergeMap, reduce } from 'rxjs/operators';
import { Tree } from '../types';
import { isLeaf } from '../types/tree';
export function treeLeafs<N extends any, T extends Tree<N>>(
options: any = {
childrenProperty: 'children'
}
): (souce: Observable<T>) => Observable<N[]> {
const childrenProp = options.childrenProperty || 'children';
return (source: Observable<T>) => source.pipe(
mergeMap((tree: T) => {
if (!tree) {
return of( [] );
} else if (isLeaf(tree, childrenProp)) {
const leaf = Object.assign({}, tree);
delete leaf[childrenProp];
return of( leaf );
} else {
return concat(
...tree[childrenProp].map((child: N) => of(child).pipe(
treeLeafs( options )
))
);
}
}),
reduce(
(leafs: N[], leaf: N | N[]) => leafs.concat( leaf ), []
)
);
}