Code coverage report for src/operator/count.ts

Statements: 100% (35 / 35)      Branches: 100% (6 / 6)      Functions: 100% (8 / 8)      Lines: 100% (32 / 32)      Ignored: none     

All files » src/operator/ » count.ts
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 63 64 65 66      1   1 1                             1 24     1 24 24     1 24   1   1 24 24   1 24 24 24     1 44 44 44 14 14 1 1     43 39       1 14 14   1  
import {Observable} from '../Observable';
import {Operator} from '../Operator';
import {Observer} from '../Observer';
import {Subscriber} from '../Subscriber';
 
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
 
/**
 * Returns an observable of a single number that represents the number of items that either:
 * Match a provided predicate function, _or_ if a predicate is not provided, the number
 * represents the total count of all items in the source observable. The count is emitted
 * by the returned observable when the source observable completes.
 * @param {function} [predicate] a boolean function to select what values are to be counted.
 * it is provided with arguments of:
 *   - `value`: the value from the source observable
 *   - `index`: the "index" of the value from the source observable
 *   - `source`: the source observable instance itself.
 * @returns {Observable} an observable of one number that represents the count as described
 * above
 */
export function count<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): Observable<number> {
  return this.lift(new CountOperator(predicate, this));
}
 
class CountOperator<T> implements Operator<T, number> {
  constructor(private predicate?: (value: T, index: number, source: Observable<T>) => boolean,
              private source?: Observable<T>) {
  }
 
  call(subscriber: Subscriber<number>): Subscriber<T> {
    return new CountSubscriber(subscriber, this.predicate, this.source);
  }
}
 
class CountSubscriber<T> extends Subscriber<T> {
  private count: number = 0;
  private index: number = 0;
 
  constructor(destination: Observer<number>,
              private predicate?: (value: T, index: number, source: Observable<T>) => boolean,
              private source?: Observable<T>) {
    super(destination);
  }
 
  protected _next(value: T): void {
    const predicate = this.predicate;
    let passed: any = true;
    if (predicate) {
      passed = tryCatch(predicate)(value, this.index++, this.source);
      if (passed === errorObject) {
        this.destination.error(passed.e);
        return;
      }
    }
    if (passed) {
      this.count += 1;
    }
  }
 
  protected _complete(): void {
    this.destination.next(this.count);
    this.destination.complete();
  }
}