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 12, 2017
1 parent c78c395 commit 82480cf
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 32 deletions.
35 changes: 3 additions & 32 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>(arr: T[], item: T, index: number) {
arr.push(item);
return arr;
}

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

0 comments on commit 82480cf

Please sign in to comment.