-
Notifications
You must be signed in to change notification settings - Fork 72
/
expand.ts
36 lines (32 loc) · 1.07 KB
/
expand.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
34
35
36
import { IterableX } from './iterablex';
export class ExpandIterable<TSource> extends IterableX<TSource> {
private _source: Iterable<TSource>;
private _fn: (value: TSource) => Iterable<TSource>;
constructor(source: Iterable<TSource>, fn: (value: TSource) => Iterable<TSource>) {
super();
this._source = source;
this._fn = fn;
}
*[Symbol.iterator]() {
let q = [this._source];
while (q.length > 0) {
let src = q.shift();
for (let item of src!) {
q.push(this._fn(item));
yield item;
}
}
}
}
/**
* Expands the sequence by recursively applying a selector function.
* @param {Iterable<T>} source Source sequence.
* @param {function(value: T): Iterable<T>} selector Selector function to retrieve the next sequence to expand
* @return {Iterable<T>} Sequence with results from the recursive expansion of the source sequence.
*/
export function expand<TSource>(
source: Iterable<TSource>,
selector: (value: TSource) => Iterable<TSource>
): IterableX<TSource> {
return new ExpandIterable<TSource>(source, selector);
}