Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(timeInterval): implement in terms of scan #3177

Merged
merged 1 commit into from Mar 30, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
58 changes: 17 additions & 41 deletions src/internal/operators/timeInterval.ts
@@ -1,48 +1,24 @@
import { Operator } from '../Operator';

import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { async } from '../scheduler/async';
import { OperatorFunction, SchedulerLike, TimeInterval as TimeIntervalInterface } from '../types';
import { SchedulerLike, OperatorFunction } from '../types';
import { scan } from './scan';
import { defer } from '../observable/defer';
import { map } from './map';

export function timeInterval<T>(scheduler: SchedulerLike = async): OperatorFunction<T, TimeInterval<T>> {
return (source: Observable<T>) => source.lift(new TimeIntervalOperator(scheduler));
}

export class TimeInterval<T> implements TimeIntervalInterface<T> {
constructor(public value: T, public interval: number) {

}
}

class TimeIntervalOperator<T> implements Operator<T, TimeInterval<T>> {
constructor(private scheduler: SchedulerLike) {

}

call(observer: Subscriber<TimeInterval<T>>, source: any): any {
return source.subscribe(new TimeIntervalSubscriber(observer, this.scheduler));
}
return (source: Observable<T>) => defer(() => {
return source.pipe(
// HACK: the typings seem off with scan
scan(
({ current }, value) => ({ value, current: scheduler.now(), last: current }),
{ current: scheduler.now(), value: undefined, last: undefined }
) as any,
map<any, TimeInterval<T>>(({ current, last, value }) => new TimeInterval(value, current - last)),
);
});
}

/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
class TimeIntervalSubscriber<T> extends Subscriber<T> {
private lastTime: number = 0;

constructor(destination: Subscriber<TimeInterval<T>>, private scheduler: SchedulerLike) {
super(destination);

this.lastTime = scheduler.now();
}

protected _next(value: T) {
let now = this.scheduler.now();
let span = now - this.lastTime;
this.lastTime = now;

this.destination.next(new TimeInterval(value, span));
}
export class TimeInterval<T> {
constructor(public value: T, public interval: number) {}
}