-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterate.ts
32 lines (28 loc) · 904 Bytes
/
iterate.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
/**
* Creates an iterator that itates through all grandchildren
*/
export function iterate<TChild, TGrandchild>(children: TChild[], grandchildKey: keyof TChild): Iterable<TGrandchild> {
return {
[Symbol.iterator]() {
let childIndex = 0;
let grandchildIndex = 0;
return {
next(): IteratorResult<TGrandchild> {
if (childIndex >= children.length) {
return { done: true, value: undefined };
}
let child = children[childIndex];
let grandchildren = child[grandchildKey] as unknown as TGrandchild[];
if (grandchildIndex >= grandchildren.length) {
childIndex++;
grandchildIndex = 0;
return this.next();
}
let grandchild = grandchildren[grandchildIndex];
grandchildIndex++;
return { value: grandchild };
}
};
},
};
}