single.js
1.73 KB
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
58
59
60
61
62
import { Subscriber } from '../Subscriber';
import { EmptyError } from '../util/EmptyError';
export function single(predicate) {
return (source) => source.lift(new SingleOperator(predicate, source));
}
class SingleOperator {
constructor(predicate, source) {
this.predicate = predicate;
this.source = source;
}
call(subscriber, source) {
return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));
}
}
class SingleSubscriber extends Subscriber {
constructor(destination, predicate, source) {
super(destination);
this.predicate = predicate;
this.source = source;
this.seenValue = false;
this.index = 0;
}
applySingleValue(value) {
if (this.seenValue) {
this.destination.error('Sequence contains more than one element');
}
else {
this.seenValue = true;
this.singleValue = value;
}
}
_next(value) {
const index = this.index++;
if (this.predicate) {
this.tryNext(value, index);
}
else {
this.applySingleValue(value);
}
}
tryNext(value, index) {
try {
if (this.predicate(value, index, this.source)) {
this.applySingleValue(value);
}
}
catch (err) {
this.destination.error(err);
}
}
_complete() {
const destination = this.destination;
if (this.index > 0) {
destination.next(this.seenValue ? this.singleValue : undefined);
destination.complete();
}
else {
destination.error(new EmptyError);
}
}
}
//# sourceMappingURL=single.js.map