Code coverage report for src/operator/takeLast.ts

Statements: 96.08% (49 / 51)      Branches: 90% (18 / 20)      Functions: 100% (8 / 8)      Lines: 95.74% (45 / 47)      Ignored: none     

All files » src/operator/ » takeLast.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 74 75 76 77  1 1 1     1 13 1   12       1 12 12 1       1 11   1   1   11 11   11 11 11     1   14 14 14 14   14 10 8 8 2 1 1     1   4 2     14     1   5 5 5   5 4     4   5   1  
import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {ArgumentOutOfRangeError} from '../util/ArgumentOutOfRangeError';
import {EmptyObservable} from '../observable/EmptyObservable';
import {Observable} from '../Observable';
 
export function takeLast<T>(total: number): Observable<T> {
  if (total === 0) {
    return new EmptyObservable<T>();
  } else {
    return this.lift(new TakeLastOperator(total));
  }
}
 
class TakeLastOperator<T> implements Operator<T, T> {
  constructor(private total: number) {
    if (this.total < 0) {
      throw new ArgumentOutOfRangeError;
    }
  }
 
  call(subscriber: Subscriber<T>): Subscriber<T> {
    return new TakeLastSubscriber(subscriber, this.total);
  }
}
 
class TakeLastSubscriber<T> extends Subscriber<T> {
  private ring: T[];
  private count: number = 0;
  private index: number = 0;
 
  constructor(destination: Subscriber<T>, private total: number) {
    super(destination);
    this.ring = new Array(total);
  }
 
  protected _next(value: T): void {
 
    let index = this.index;
    const ring = this.ring;
    const total = this.total;
    const count = this.count;
 
    if (total > 1) {
      if (count < total) {
        this.count = count + 1;
        this.index = index + 1;
      } else if (index === 0) {
        this.index = ++index;
      } else Iif (index < total) {
        this.index = index + 1;
      } else  {
        this.index = index = 0;
      }
    } else if (count < total) {
      this.count = total;
    }
 
    ring[index] = value;
  }
 
  protected _complete(): void {
 
    let iter = -1;
    const { ring, count, total, destination } = this;
    let index = (total === 1 || count < total) ? 0 : this.index - 1;
 
    while (++iter < count) {
      Iif (iter + index === total) {
        index = total - iter;
      }
      destination.next(ring[iter + index]);
    }
    destination.complete();
  }
}