Skip to content

Commit

Permalink
feat(toArray): add higher-order lettable version of toArray
Browse files Browse the repository at this point in the history
  • Loading branch information
benlesh committed Jul 5, 2017
1 parent 0b73208 commit a03a50c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 33 deletions.
37 changes: 4 additions & 33 deletions src/operator/toArray.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,12 @@
import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';

import { Observable } from '../Observable';
import { toArray as higherOrder } from '../operators';

/**
* @return {Observable<any[]>|WebSocketSubject<T>|Observable<T>}
* @method toArray
* @owner Observable
*/
export function toArray<T>(this: Observable<T>): Observable<T[]> {
return this.lift(new ToArrayOperator());
}

class ToArrayOperator<T> implements Operator<T, T[]> {
call(subscriber: Subscriber<T[]>, source: any): any {
return source.subscribe(new ToArraySubscriber(subscriber));
}
}

/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class ToArraySubscriber<T> extends Subscriber<T> {

private array: T[] = [];

constructor(destination: Subscriber<T[]>) {
super(destination);
}

protected _next(x: T) {
this.array.push(x);
}

protected _complete() {
this.destination.next(this.array);
this.destination.complete();
}
}
return higherOrder()(this);
}
1 change: 1 addition & 0 deletions src/operators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export { switchAll } from './switchAll';
export { switchMap } from './switchMap';
export { takeLast } from './takeLast';
export { tap } from './tap';
export { toArray } from './toArray';
export { window } from './window';
export { windowCount } from './windowCount';
export { windowTime } from './windowTime';
Expand Down
11 changes: 11 additions & 0 deletions src/operators/toArray.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { reduce } from './reduce';
import { OperatorFunction } from '../interfaces';

function toArrayReducer<T>(acc: T[], value: T) {
acc.push(value);
return acc;
}

export function toArray<T>(): OperatorFunction<T, T[]> {
return reduce(toArrayReducer, []);
}

0 comments on commit a03a50c

Please sign in to comment.