Code coverage report for src/operator/windowCount.ts

Statements: 100% (52 / 52)      Branches: 100% (10 / 10)      Functions: 100% (9 / 9)      Lines: 100% (48 / 48)      Ignored: none     

All files » src/operator/ » windowCount.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 67 68 69 70 71 72 73  1   1   1 12 10     1   10 10     1 10   1   1 10 10   10 10 10 10 10 10 10     1 34 34 34 34 34   34 50   34 34 17   34 22 22 22 22       1 2 2 4   2     1 4 4 5   4   1  
import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {Subject} from '../Subject';
 
export function windowCount<T>(windowSize: number,
                               startWindowEvery: number = 0): Observable<Observable<T>> {
  return this.lift(new WindowCountOperator(windowSize, startWindowEvery));
}
 
class WindowCountOperator<T> implements Operator<T, Observable<T>> {
 
  constructor(private windowSize: number,
              private startWindowEvery: number) {
  }
 
  call(subscriber: Subscriber<Observable<T>>): Subscriber<T> {
    return new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery);
  }
}
 
class WindowCountSubscriber<T> extends Subscriber<T> {
  private windows: Subject<T>[] = [ new Subject<T>() ];
  private count: number = 0;
 
  constructor(protected destination: Subscriber<Observable<T>>,
              private windowSize: number,
              private startWindowEvery: number) {
    super(destination);
    const firstWindow = this.windows[0];
    destination.add(firstWindow);
    destination.next(firstWindow);
  }
 
  protected _next(value: T) {
    const startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;
    const destination = this.destination;
    const windowSize = this.windowSize;
    const windows = this.windows;
    const len = windows.length;
 
    for (let i = 0; i < len; i++) {
      windows[i].next(value);
    }
    const c = this.count - windowSize + 1;
    if (c >= 0 && c % startWindowEvery === 0) {
      windows.shift().complete();
    }
    if (++this.count % startWindowEvery === 0) {
      const window = new Subject<T>();
      windows.push(window);
      destination.add(window);
      destination.next(window);
    }
  }
 
  protected _error(err: any) {
    const windows = this.windows;
    while (windows.length > 0) {
      windows.shift().error(err);
    }
    this.destination.error(err);
  }
 
  protected _complete() {
    const windows = this.windows;
    while (windows.length > 0) {
      windows.shift().complete();
    }
    this.destination.complete();
  }
}