-
Notifications
You must be signed in to change notification settings - Fork 72
/
catchwith.ts
57 lines (50 loc) · 1.63 KB
/
catchwith.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
import { IterableX } from './iterablex';
import { returnIterator } from '../internal/returniterator';
export class CatchWithIterable<TSource> extends IterableX<TSource> {
private _source: Iterable<TSource>;
private _handler: (error: any) => Iterable<TSource>;
constructor(source: Iterable<TSource>, handler: (error: any) => Iterable<TSource>) {
super();
this._source = source;
this._handler = handler;
}
*[Symbol.iterator]() {
let err: Iterable<TSource> | undefined,
hasError = false,
it = this._source[Symbol.iterator]();
while (1) {
let c = <IteratorResult<TSource>>{};
try {
c = it.next();
if (c.done) {
returnIterator(it);
break;
}
} catch (e) {
err = this._handler(e);
hasError = true;
returnIterator(it);
break;
}
yield c.value;
}
if (hasError) {
for (let item of err!) {
yield item;
}
}
}
}
/**
* Creates a sequence that corresponds to the source sequence, concatenating it with the sequence resulting from
* calling an exception handler function in case of an error.
* @param {Iterable<TSource>} source Source sequence
* @param {function(error: any): Iterable<TSource>} handler Handler to invoke when an exception of the specified type occurs.
* @return {Iterable<TSource>} Source sequence, concatenated with an exception handler result sequence in case of an error.
*/
export function catchWith<TSource>(
source: Iterable<TSource>,
handler: (error: any) => Iterable<TSource>
): IterableX<TSource> {
return new CatchWithIterable<TSource>(source, handler);
}