1 import { Operator } from '../Operator';
2 import { Subscriber } from '../Subscriber';
3 import { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';
4 import { Observable } from '../Observable';
5 import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
8 * Skip the last `count` values emitted by the source Observable.
12 * `skipLast` returns an Observable that accumulates a queue with a length
13 * enough to store the first `count` values. As more values are received,
14 * values are taken from the front of the queue and produced on the result
15 * sequence. This causes values to be delayed.
18 * Skip the last 2 values of an Observable with many values
20 * import { range } from 'rxjs';
21 * import { skipLast } from 'rxjs/operators';
23 * const many = range(1, 5);
24 * const skipLastTwo = many.pipe(skipLast(2));
25 * skipLastTwo.subscribe(x => console.log(x));
32 * @see {@link skipUntil}
33 * @see {@link skipWhile}
36 * @throws {ArgumentOutOfRangeError} When using `skipLast(i)`, it throws
37 * ArgumentOutOrRangeError if `i < 0`.
39 * @param {number} count Number of elements to skip from the end of the source Observable.
40 * @returns {Observable<T>} An Observable that skips the last count values
41 * emitted by the source Observable.
45 export function skipLast<T>(count: number): MonoTypeOperatorFunction<T> {
46 return (source: Observable<T>) => source.lift(new SkipLastOperator(count));
49 class SkipLastOperator<T> implements Operator<T, T> {
50 constructor(private _skipCount: number) {
51 if (this._skipCount < 0) {
52 throw new ArgumentOutOfRangeError;
56 call(subscriber: Subscriber<T>, source: any): TeardownLogic {
57 if (this._skipCount === 0) {
58 // If we don't want to skip any values then just subscribe
59 // to Subscriber without any further logic.
60 return source.subscribe(new Subscriber(subscriber));
62 return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount));
68 * We need this JSDoc comment for affecting ESDoc.
72 class SkipLastSubscriber<T> extends Subscriber<T> {
74 private _count: number = 0;
76 constructor(destination: Subscriber<T>, private _skipCount: number) {
78 this._ring = new Array<T>(_skipCount);
81 protected _next(value: T): void {
82 const skipCount = this._skipCount;
83 const count = this._count++;
85 if (count < skipCount) {
86 this._ring[count] = value;
88 const currentIndex = count % skipCount;
89 const ring = this._ring;
90 const oldValue = ring[currentIndex];
92 ring[currentIndex] = value;
93 this.destination.next(oldValue);