Skip to content

Commit

Permalink
fix(scan): scan now behaves like RxJS 4 scan
Browse files Browse the repository at this point in the history
- scan no longer always emits the first value ignoring the seed
- scan no longer tries to emitted the scanned value at completion
  • Loading branch information
benlesh committed Oct 16, 2015
1 parent bc1eecd commit 27f9c09
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions src/operators/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import tryCatch from '../util/tryCatch';
import {errorObject} from '../util/errorObject';

export default function scan<T, R>(project: (acc: R, x: T) => R, acc?: R) {
return this.lift(new ScanOperator(project));
return this.lift(new ScanOperator(project, acc));
}

class ScanOperator<T, R> implements Operator<T, R> {
Expand All @@ -25,36 +25,40 @@ class ScanOperator<T, R> implements Operator<T, R> {
}

class ScanSubscriber<T, R> extends Subscriber<T> {
private _acc: R;

get acc(): R {
return this._acc;
}

set acc(value: R) {
this.accumulatorSet = true;
this._acc = value;
}

accumulatorSet: boolean = false;

acc: R;
hasSeed: boolean;
hasValue: boolean = false;
project: (acc: R, x: T) => R;

constructor(destination: Subscriber<T>, project: (acc: R, x: T) => R, acc?: R) {
super(destination);
this.acc = acc;
this.project = project;
this.hasSeed = typeof acc !== 'undefined';
this.accumulatorSet = typeof acc !== 'undefined';
}

_next(x) {
if (this.hasValue || (this.hasValue = this.hasSeed)) {
if (!this.accumulatorSet) {
this.acc = x;
this.destination.next(x);
} else {
const result = tryCatch(this.project).call(this, this.acc, x);
if (result === errorObject) {
this.destination.error(errorObject.e);
} else {
this.destination.next(this.acc = result);
this.acc = result;
this.destination.next(this.acc);
}
} else {
return this.destination.next((this.hasValue = true) && (this.acc = x));
}
}

_complete() {
if (!this.hasValue && this.hasSeed) {
this.destination.next(this.acc);
}
this.destination.complete();
}
}

0 comments on commit 27f9c09

Please sign in to comment.