1+ import Operator from '../Operator' ;
2+ import Observer from '../Observer' ;
3+ import Subscriber from '../Subscriber' ;
4+ import Observable from '../Observable' ;
5+ import Subject from '../Subject' ;
6+ import Subscription from '../Subscription' ;
7+ import Scheduler from '../Scheduler' ;
8+
9+ import tryCatch from '../util/tryCatch' ;
10+ import { errorObject } from '../util/errorObject' ;
11+ import bindCallback from '../util/bindCallback' ;
12+
13+ export default function windowCount < T > ( windowSize : number , startWindowEvery : number = 0 ) : Observable < Observable < T > > {
14+ return this . lift ( new WindowCountOperator ( windowSize , startWindowEvery ) ) ;
15+ }
16+
17+ export class WindowCountOperator < T , R > implements Operator < T , R > {
18+
19+ constructor ( private windowSize : number , private startWindowEvery : number ) {
20+ }
21+
22+ call ( observer : Observer < T > ) : Observer < T > {
23+ return new WindowCountSubscriber ( observer , this . windowSize , this . startWindowEvery ) ;
24+ }
25+ }
26+
27+ export class WindowCountSubscriber < T > extends Subscriber < T > {
28+ private windows : { count : number , window : Subject < T > } [ ] = [ ] ;
29+ private count : number = 0 ;
30+
31+ constructor ( destination : Observer < T > , private windowSize : number , private startWindowEvery : number ) {
32+ super ( destination ) ;
33+ }
34+
35+ _next ( value : T ) {
36+ const count = ( this . count += 1 ) ;
37+ const startWindowEvery = this . startWindowEvery ;
38+ const windowSize = this . windowSize ;
39+ const windows = this . windows ;
40+
41+ if ( startWindowEvery && count % this . startWindowEvery === 0 ) {
42+ let window = new Subject < T > ( ) ;
43+ windows . push ( { count : 0 , window } ) ;
44+ this . destination . next ( window ) ;
45+ }
46+
47+ const len = windows . length ;
48+ for ( let i = 0 ; i < len ; i ++ ) {
49+ let w = windows [ i ] ;
50+ const window = w . window ;
51+ window . next ( value ) ;
52+ if ( windowSize === ( w . count += 1 ) ) {
53+ window . complete ( ) ;
54+ }
55+ }
56+ }
57+
58+ _error ( err : any ) {
59+ const windows = this . windows ;
60+ while ( windows . length > 0 ) {
61+ windows . shift ( ) . window . error ( err ) ;
62+ }
63+ this . destination . error ( err ) ;
64+ }
65+
66+ _complete ( ) {
67+ const windows = this . windows ;
68+ while ( windows . length > 0 ) {
69+ windows . shift ( ) . window . complete ( ) ;
70+ }
71+ this . destination . complete ( ) ;
72+ }
73+ }
0 commit comments