@@ -3,6 +3,10 @@ import { Subscriber } from '../Subscriber';
33import { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError' ;
44import { Observable } from '../Observable' ;
55import { MonoTypeOperatorFunction , TeardownLogic } from '../types' ;
6+ import { filter } from './filter' ;
7+ import { throwIfEmpty } from './throwIfEmpty' ;
8+ import { defaultIfEmpty } from './defaultIfEmpty' ;
9+ import { take } from './take' ;
610
711/**
812 * Emits the single value at the specified `index` in a sequence of emissions
@@ -47,49 +51,13 @@ import { MonoTypeOperatorFunction, TeardownLogic } from '../types';
4751 * @owner Observable
4852 */
4953export function elementAt < T > ( index : number , defaultValue ?: T ) : MonoTypeOperatorFunction < T > {
50- return ( source : Observable < T > ) => source . lift ( new ElementAtOperator ( index , defaultValue ) ) ;
51- }
52-
53- class ElementAtOperator < T > implements Operator < T , T > {
54-
55- constructor ( private index : number , private defaultValue ?: T ) {
56- if ( index < 0 ) {
57- throw new ArgumentOutOfRangeError ;
58- }
59- }
60-
61- call ( subscriber : Subscriber < T > , source : any ) : TeardownLogic {
62- return source . subscribe ( new ElementAtSubscriber ( subscriber , this . index , this . defaultValue ) ) ;
63- }
64- }
65-
66- /**
67- * We need this JSDoc comment for affecting ESDoc.
68- * @ignore
69- * @extends {Ignored }
70- */
71- class ElementAtSubscriber < T > extends Subscriber < T > {
72-
73- constructor ( destination : Subscriber < T > , private index : number , private defaultValue ?: T ) {
74- super ( destination ) ;
75- }
76-
77- protected _next ( x : T ) {
78- if ( this . index -- === 0 ) {
79- this . destination . next ( x ) ;
80- this . destination . complete ( ) ;
81- }
82- }
83-
84- protected _complete ( ) {
85- const destination = this . destination ;
86- if ( this . index >= 0 ) {
87- if ( typeof this . defaultValue !== 'undefined' ) {
88- destination . next ( this . defaultValue ) ;
89- } else {
90- destination . error ( new ArgumentOutOfRangeError ) ;
91- }
92- }
93- destination . complete ( ) ;
94- }
54+ if ( index < 0 ) { throw new ArgumentOutOfRangeError ( ) ; }
55+ const hasDefaultValue = arguments . length >= 2 ;
56+ return ( source : Observable < T > ) => source . pipe (
57+ filter ( ( v , i ) => i === index ) ,
58+ take ( 1 ) ,
59+ hasDefaultValue
60+ ? defaultIfEmpty ( defaultValue )
61+ : throwIfEmpty ( ( ) => new ArgumentOutOfRangeError ( ) ) ,
62+ ) ;
9563}
0 commit comments