[6a3a178] | 1 | import { Subscriber } from '../Subscriber';
|
---|
| 2 | import { EmptyError } from '../util/EmptyError';
|
---|
| 3 | export function single(predicate) {
|
---|
| 4 | return (source) => source.lift(new SingleOperator(predicate, source));
|
---|
| 5 | }
|
---|
| 6 | class SingleOperator {
|
---|
| 7 | constructor(predicate, source) {
|
---|
| 8 | this.predicate = predicate;
|
---|
| 9 | this.source = source;
|
---|
| 10 | }
|
---|
| 11 | call(subscriber, source) {
|
---|
| 12 | return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));
|
---|
| 13 | }
|
---|
| 14 | }
|
---|
| 15 | class SingleSubscriber extends Subscriber {
|
---|
| 16 | constructor(destination, predicate, source) {
|
---|
| 17 | super(destination);
|
---|
| 18 | this.predicate = predicate;
|
---|
| 19 | this.source = source;
|
---|
| 20 | this.seenValue = false;
|
---|
| 21 | this.index = 0;
|
---|
| 22 | }
|
---|
| 23 | applySingleValue(value) {
|
---|
| 24 | if (this.seenValue) {
|
---|
| 25 | this.destination.error('Sequence contains more than one element');
|
---|
| 26 | }
|
---|
| 27 | else {
|
---|
| 28 | this.seenValue = true;
|
---|
| 29 | this.singleValue = value;
|
---|
| 30 | }
|
---|
| 31 | }
|
---|
| 32 | _next(value) {
|
---|
| 33 | const index = this.index++;
|
---|
| 34 | if (this.predicate) {
|
---|
| 35 | this.tryNext(value, index);
|
---|
| 36 | }
|
---|
| 37 | else {
|
---|
| 38 | this.applySingleValue(value);
|
---|
| 39 | }
|
---|
| 40 | }
|
---|
| 41 | tryNext(value, index) {
|
---|
| 42 | try {
|
---|
| 43 | if (this.predicate(value, index, this.source)) {
|
---|
| 44 | this.applySingleValue(value);
|
---|
| 45 | }
|
---|
| 46 | }
|
---|
| 47 | catch (err) {
|
---|
| 48 | this.destination.error(err);
|
---|
| 49 | }
|
---|
| 50 | }
|
---|
| 51 | _complete() {
|
---|
| 52 | const destination = this.destination;
|
---|
| 53 | if (this.index > 0) {
|
---|
| 54 | destination.next(this.seenValue ? this.singleValue : undefined);
|
---|
| 55 | destination.complete();
|
---|
| 56 | }
|
---|
| 57 | else {
|
---|
| 58 | destination.error(new EmptyError);
|
---|
| 59 | }
|
---|
| 60 | }
|
---|
| 61 | }
|
---|
| 62 | //# sourceMappingURL=single.js.map |
---|