-
Notifications
You must be signed in to change notification settings - Fork 2
/
first.ts
48 lines (43 loc) · 1.23 KB
/
first.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
import { Operator, Observer } from '../index';
import { createSource } from '../sources';
import subscribe from '../utils/subscribe';
/**
* Emits only the first value (or the first value that meets some condition) emitted by the source
*
* @param predicate - function for determining if an item meets a specified condition
* @param defaultValue - default value to emit if source is empty
* @return callbag operator
*
* @public
*/
function first<I, D>(
predicate?: ((value: I) => boolean) | null,
defaultValue?: D,
): Operator<I, I | D> {
return source => {
return createSource((next, complete, error) => {
let unsubscribe = () => {};
const observer: Observer<I> = {
next: value => {
if (!predicate || predicate(value)) {
unsubscribe();
next(value);
complete();
}
},
error,
complete: () => {
if (defaultValue !== undefined) {
next(defaultValue);
complete();
} else {
error(new Error('operator/first: source complete without any value'));
}
},
};
unsubscribe = subscribe(source)(observer);
return unsubscribe;
});
};
}
export default first;