-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathtapWithIndex.ts
51 lines (49 loc) · 1.68 KB
/
tapWithIndex.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
/**
* @license Use of this source code is governed by an MIT-style license that
* can be found in the LICENSE file at https://github.com/cartant/rxjs-etc
*/
import { defer, MonoTypeOperatorFunction, noop, PartialObserver } from "rxjs";
import { tap } from "rxjs/operators";
export function tapWithIndex<T>(
next?: (tuple: [T, number]) => void,
error?: (error: any) => void,
complete?: () => void
): MonoTypeOperatorFunction<T>;
export function tapWithIndex<T>(
observer: PartialObserver<[T, number]>
): MonoTypeOperatorFunction<T>;
export function tapWithIndex<T>(
nextOrObserver?:
| ((tuple: [T, number]) => void)
| PartialObserver<[T, number]>,
error?: (error: any) => void,
complete?: () => void
): MonoTypeOperatorFunction<T> {
return (source) =>
defer(() => {
/*tslint:disable-next-line:no-unused-declaration*/
let index = -1;
let context: any;
let handleNext: ([value, index]: [T, number]) => void;
let handleError: (error: any) => void;
let handleComplete: () => void;
if (nextOrObserver && typeof nextOrObserver !== "function") {
context = nextOrObserver;
handleNext = nextOrObserver.next || noop;
handleError = nextOrObserver.error || noop;
handleComplete = nextOrObserver.complete || noop;
} else {
context = undefined;
handleNext = nextOrObserver || noop;
handleError = error || noop;
handleComplete = complete || noop;
}
return source.pipe(
tap(
(value) => handleNext.call(context, [value, ++index]),
(error) => handleError.call(context, error),
() => handleComplete.call(context)
)
);
});
}