Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

skipWhile.ts 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { Observable } from '../Observable';
  2. import { Operator } from '../Operator';
  3. import { Subscriber } from '../Subscriber';
  4. import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
  5. /**
  6. * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
  7. * true, but emits all further source items as soon as the condition becomes false.
  8. *
  9. * ![](skipWhile.png)
  10. *
  11. * @param {Function} predicate - A function to test each item emitted from the source Observable.
  12. * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
  13. * specified predicate becomes false.
  14. * @method skipWhile
  15. * @owner Observable
  16. */
  17. export function skipWhile<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T> {
  18. return (source: Observable<T>) => source.lift(new SkipWhileOperator(predicate));
  19. }
  20. class SkipWhileOperator<T> implements Operator<T, T> {
  21. constructor(private predicate: (value: T, index: number) => boolean) {
  22. }
  23. call(subscriber: Subscriber<T>, source: any): TeardownLogic {
  24. return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
  25. }
  26. }
  27. /**
  28. * We need this JSDoc comment for affecting ESDoc.
  29. * @ignore
  30. * @extends {Ignored}
  31. */
  32. class SkipWhileSubscriber<T> extends Subscriber<T> {
  33. private skipping: boolean = true;
  34. private index: number = 0;
  35. constructor(destination: Subscriber<T>,
  36. private predicate: (value: T, index: number) => boolean) {
  37. super(destination);
  38. }
  39. protected _next(value: T): void {
  40. const destination = this.destination;
  41. if (this.skipping) {
  42. this.tryCallPredicate(value);
  43. }
  44. if (!this.skipping) {
  45. destination.next(value);
  46. }
  47. }
  48. private tryCallPredicate(value: T): void {
  49. try {
  50. const result = this.predicate(value, this.index++);
  51. this.skipping = Boolean(result);
  52. } catch (err) {
  53. this.destination.error(err);
  54. }
  55. }
  56. }