every.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { Subscriber } from '../Subscriber';
  2. /**
  3. * Returns an Observable that emits whether or not every item of the source satisfies the condition specified.
  4. *
  5. * @example <caption>A simple example emitting true if all elements are less than 5, false otherwise</caption>
  6. * Observable.of(1, 2, 3, 4, 5, 6)
  7. * .every(x => x < 5)
  8. * .subscribe(x => console.log(x)); // -> false
  9. *
  10. * @param {function} predicate A function for determining if an item meets a specified condition.
  11. * @param {any} [thisArg] Optional object to use for `this` in the callback.
  12. * @return {Observable} An Observable of booleans that determines if all items of the source Observable meet the condition specified.
  13. * @method every
  14. * @owner Observable
  15. */
  16. export function every(predicate, thisArg) {
  17. return (source) => source.lift(new EveryOperator(predicate, thisArg, source));
  18. }
  19. class EveryOperator {
  20. constructor(predicate, thisArg, source) {
  21. this.predicate = predicate;
  22. this.thisArg = thisArg;
  23. this.source = source;
  24. }
  25. call(observer, source) {
  26. return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));
  27. }
  28. }
  29. /**
  30. * We need this JSDoc comment for affecting ESDoc.
  31. * @ignore
  32. * @extends {Ignored}
  33. */
  34. class EverySubscriber extends Subscriber {
  35. constructor(destination, predicate, thisArg, source) {
  36. super(destination);
  37. this.predicate = predicate;
  38. this.thisArg = thisArg;
  39. this.source = source;
  40. this.index = 0;
  41. this.thisArg = thisArg || this;
  42. }
  43. notifyComplete(everyValueMatch) {
  44. this.destination.next(everyValueMatch);
  45. this.destination.complete();
  46. }
  47. _next(value) {
  48. let result = false;
  49. try {
  50. result = this.predicate.call(this.thisArg, value, this.index++, this.source);
  51. }
  52. catch (err) {
  53. this.destination.error(err);
  54. return;
  55. }
  56. if (!result) {
  57. this.notifyComplete(false);
  58. }
  59. }
  60. _complete() {
  61. this.notifyComplete(true);
  62. }
  63. }
  64. //# sourceMappingURL=every.js.map