-
Notifications
You must be signed in to change notification settings - Fork 74
/
flatmap.ts
143 lines (130 loc) · 4.86 KB
/
flatmap.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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import { AsyncIterableX } from '../asynciterablex';
import { bindCallback } from '../../util/bindcallback';
import { OperatorAsyncFunction } from '../../interfaces';
const NEVER_PROMISE = new Promise(() => {
/**/
});
type InnerResult<T> = { value: T; done: boolean; index: number; type: 'inner' };
type OuterResult<T> = { value: AsyncIterable<T>; done: boolean; index: number; type: 'outer' };
function isOuterResult<T>(x: any): x is OuterResult<T> {
return x.type === 'outer';
}
function wrapInnerValuePromiseWithIndex<T>(promise: Promise<IteratorResult<T>>, index: number) {
return promise.then(({ value, done }) => ({ value, done, index, type: 'inner' })) as Promise<
InnerResult<T>
>;
}
function wrapOuterValuePromiseWithIndex<T, R>(
promise: Promise<IteratorResult<T>>,
index: number,
selector: (value: T) => AsyncIterable<R> | Promise<AsyncIterable<R>>
) {
return promise.then(
async ({ value, done }) =>
({
done,
index,
type: 'outer',
value: !done ? await selector(value) : null
} as OuterResult<R>)
);
}
export class FlatMapAsyncIterable<TSource, TResult> extends AsyncIterableX<TResult> {
private _maxConcurrent: number;
private _source: AsyncIterable<TSource>;
private _selector: (value: TSource) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>;
constructor(
source: AsyncIterable<TSource>,
selector: (value: TSource) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>,
maxConcurrent = Infinity
) {
super();
this._source = source;
this._selector = selector;
this._maxConcurrent = maxConcurrent;
}
async *[Symbol.asyncIterator]() {
const { _maxConcurrent, _source, _selector } = this;
const outer = _source[Symbol.asyncIterator]();
const inners = [] as AsyncIterator<TResult>[];
const queued = [] as AsyncIterable<TResult>[];
const promises = [] as Promise<OuterResult<TResult> | InnerResult<TResult>>[];
promises[0] = wrapOuterValuePromiseWithIndex(outer.next(), 0, _selector);
let active = 0;
let outerDone = false;
try {
do {
const res = await Promise.race(promises);
if (isOuterResult<TResult>(res)) {
const { done, value } = res as OuterResult<TResult>;
if ((outerDone = done)) {
promises[0] = <Promise<OuterResult<TResult>>>NEVER_PROMISE;
} else {
const itr = (inners[active++] = value[Symbol.asyncIterator]());
promises[active] = wrapInnerValuePromiseWithIndex(itr.next(), active);
if (active >= _maxConcurrent) {
queued.push(value);
promises[0] = <Promise<OuterResult<TResult>>>NEVER_PROMISE;
} else {
promises[0] = wrapOuterValuePromiseWithIndex(outer.next(), 0, _selector);
}
}
} else {
const { done, value, index } = res as InnerResult<TResult>;
if (!done) {
const itr = inners[index - 1];
promises[index] = wrapInnerValuePromiseWithIndex(itr.next(), index);
yield value;
} else if (queued.length > 0) {
const it = queued.shift()!;
const itr = (inners[index - 1] = it[Symbol.asyncIterator]());
promises[index] = wrapInnerValuePromiseWithIndex(itr.next(), index);
} else {
--active;
inners[index - 1] = <any>null;
promises[index] = <Promise<InnerResult<TResult>>>NEVER_PROMISE;
if (!outerDone) {
promises[0] = wrapOuterValuePromiseWithIndex(outer.next(), 0, _selector);
}
}
}
} while (!outerDone || active > 0);
} catch (e) {
throw e;
} finally {
try {
await Promise.all<any>(
[outer, ...inners].map(it => it && typeof it.return === 'function' && it.return())
);
} catch (e) {
/* ignored */
}
}
}
}
export function flatMap<TSource, TResult>(
selector: (value: TSource) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>,
thisArg?: any
): OperatorAsyncFunction<TSource, TResult>;
export function flatMap<TSource, TResult>(
selector: (value: TSource) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>,
maxConcurrent: number,
thisArg?: any
): OperatorAsyncFunction<TSource, TResult>;
export function flatMap<TSource, TResult>(
selector: (value: TSource) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>,
maxConcurrent?: number,
thisArg?: any
): OperatorAsyncFunction<TSource, TResult> {
if (arguments.length === 2 && typeof maxConcurrent !== 'number') {
thisArg = maxConcurrent;
maxConcurrent = undefined;
}
return function flatMapOperatorFunction(source: AsyncIterable<TSource>): AsyncIterableX<TResult> {
return new FlatMapAsyncIterable<TSource, TResult>(
source,
bindCallback(selector, thisArg, 1),
maxConcurrent
);
};
}