-
Notifications
You must be signed in to change notification settings - Fork 72
/
tap.ts
53 lines (47 loc) · 1.43 KB
/
tap.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
import { IterableX } from './iterablex';
import { PartialObserver } from '../observer';
export class TapIterable<TSource> extends IterableX<TSource> {
private _source: Iterable<TSource>;
private _observer: PartialObserver<TSource>;
constructor(source: Iterable<TSource>, observer: PartialObserver<TSource>) {
super();
this._source = source;
this._observer = observer;
}
*[Symbol.iterator]() {
const it = this._source[Symbol.iterator]();
while (1) {
let next;
try {
next = it.next();
if (next.done) {
break;
}
} catch (e) {
if (this._observer.error) {
this._observer.error(e);
}
throw e;
}
if (this._observer.next) {
this._observer.next(next.value);
}
yield next.value;
}
if (this._observer.complete) {
this._observer.complete();
}
}
}
/**
* Lazily invokes observer methods for each value in the sequence, and upon successful or exceptional termination.
* @param {Iterable<TSource>} source Source sequence.
* @param {PartialObserver<TSource>} observer Observer to invoke notification calls on.<
* @return {Ierable<TSource>} Sequence exhibiting the side-effects of observer method invocation upon iteration.
*/
export function tap<TSource>(
source: Iterable<TSource>,
observer: PartialObserver<TSource>
): IterableX<TSource> {
return new TapIterable<TSource>(source, observer);
}