single.js 1.1 KB

123456789101112131415161718192021222324252627282930
  1. import { EmptyError } from '../util/EmptyError';
  2. import { SequenceError } from '../util/SequenceError';
  3. import { NotFoundError } from '../util/NotFoundError';
  4. import { operate } from '../util/lift';
  5. import { createOperatorSubscriber } from './OperatorSubscriber';
  6. export function single(predicate) {
  7. return operate(function (source, subscriber) {
  8. var hasValue = false;
  9. var singleValue;
  10. var seenValue = false;
  11. var index = 0;
  12. source.subscribe(createOperatorSubscriber(subscriber, function (value) {
  13. seenValue = true;
  14. if (!predicate || predicate(value, index++, source)) {
  15. hasValue && subscriber.error(new SequenceError('Too many matching values'));
  16. hasValue = true;
  17. singleValue = value;
  18. }
  19. }, function () {
  20. if (hasValue) {
  21. subscriber.next(singleValue);
  22. subscriber.complete();
  23. }
  24. else {
  25. subscriber.error(seenValue ? new NotFoundError('No matching values') : new EmptyError());
  26. }
  27. }));
  28. });
  29. }
  30. //# sourceMappingURL=single.js.map