Code coverage report for src/operator/windowCount.ts

Statements: 100% (47 / 47)      Branches: 100% (10 / 10)      Functions: 100% (9 / 9)      Lines: 100% (44 / 44)      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  1   1   1 8 7     1   7 7     1 7   1   1 7 7   1 7 7 7 7     1 19 19 19 19   19 33   19 19 12   19 16 16 16       1 2 2 4   2     1 3 3 4   3   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, R> implements Operator<T, R> {
 
  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(destination: Subscriber<Observable<T>>,
              private windowSize: number,
              private startWindowEvery: number) {
    super(destination);
    destination.next(this.windows[0]);
  }
 
  _next(value: T) {
    const startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;
    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) {
      let window = new Subject<T>();
      windows.push(window);
      this.destination.next(window);
    }
  }
 
  _error(err: any) {
    const windows = this.windows;
    while (windows.length > 0) {
      windows.shift().error(err);
    }
    this.destination.error(err);
  }
 
  _complete() {
    const windows = this.windows;
    while (windows.length > 0) {
      windows.shift().complete();
    }
    this.destination.complete();
  }
}