-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer-while.ts
50 lines (46 loc) · 1.43 KB
/
buffer-while.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
import { Observable, OperatorFunction } from 'rxjs';
export function bufferWhile<T, R extends T>(
predicate: (value: T, index: number) => value is R
): OperatorFunction<T, R[]>;
export function bufferWhile<T, R extends T>(
predicate: (value: T, index: number) => value is R,
inclusive: boolean
): OperatorFunction<T, R[]>;
export function bufferWhile<T>(predicate: (value: T, index: number) => boolean): OperatorFunction<T, T[]>;
export function bufferWhile<T>(
predicate: (value: T, index: number) => boolean,
inclusive: boolean
): OperatorFunction<T, T[]>;
export function bufferWhile<T>(
predicate: (value: T, index: number) => boolean,
inclusive = false
): OperatorFunction<T, T[]> {
return (source: Observable<T>) =>
new Observable((destination) => {
let buffer: T[] = [];
let index = 0;
const emitBuffer = (firstValue?: T) => {
destination.next(buffer);
buffer = firstValue ? [firstValue] : [];
};
return source.subscribe({
next: (value) => {
if (predicate(value, index++)) {
buffer.push(value);
} else {
if (inclusive) {
buffer.push(value);
emitBuffer();
} else {
emitBuffer(value);
}
}
},
error: (err) => destination.error(err),
complete: () => {
emitBuffer();
destination.complete();
},
});
});
}