Skip to content

Commit

Permalink
feat(operator): implement skip operator with SkipMachine
Browse files Browse the repository at this point in the history
  • Loading branch information
Andre Medeiros committed Feb 25, 2016
1 parent 6e1d0db commit 32dd8ac
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {Machine} from './Machine';
import {MapMachine} from './operator/MapMachine';
import {FilterMachine} from './operator/FilterMachine';
import {TakeMachine} from './operator/TakeMachine';
import {SkipMachine} from './operator/SkipMachine';

export class Stream<T> implements Observer<T> {
public observers: Array<Observer<T>>;
Expand Down Expand Up @@ -58,4 +59,8 @@ export class Stream<T> implements Observer<T> {
take(amount: number): Stream<T> {
return new Stream<T>(new TakeMachine(amount, this));
}

skip(amount: number): Stream<T> {
return new Stream<T>(new SkipMachine(amount, this));
}
}
28 changes: 28 additions & 0 deletions src/operator/SkipMachine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import {Observer} from '../Observer';
import {Machine} from '../Machine';
import {Stream} from '../Stream';

export class SkipMachine<T> implements Machine<T> {
public proxy: Observer<T>;
public skipped: number;

constructor(public max: number,
public inStream: Stream<T>) {
this.skipped = 0;
}

start(outStream: Observer<T>): void {
this.proxy = {
next: (t: T) => {
if (this.skipped++ >= this.max) outStream.next(t);
},
error: outStream.error,
complete: outStream.complete,
};
this.inStream.subscribe(this.proxy);
}

stop(): void {
this.inStream.unsubscribe(this.proxy);
}
}
19 changes: 19 additions & 0 deletions tests/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,22 @@ describe('Stream.prototype.take', () => {
stream.subscribe(observer);
});
});

describe('Stream.prototype.skip', () => {
it('should allow specifying max amount to skip from input stream', (done) => {
const stream = xs.interval(50).skip(4)
const expected = [4, 5, 6];
let observer = {
next: (x: number) => {
assert.equal(x, expected.shift());
if (expected.length === 0) {
stream.unsubscribe(observer);
done();
}
},
error: done.fail,
complete: done.fail,
};
stream.subscribe(observer);
});
});

0 comments on commit 32dd8ac

Please sign in to comment.