Skip to content

Commit

Permalink
fix(single): predicate function receives indicies starting at 0 (#2396)
Browse files Browse the repository at this point in the history
If the user is relying on indicies starting at 1 than this could be a BC. Otherwise now it's

compatible with RxJS 4.
  • Loading branch information
martinsik authored and benlesh committed Feb 20, 2017
1 parent b9f611a commit c81882f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
18 changes: 18 additions & 0 deletions spec/operators/single-spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {expect} from 'chai';
import * as Rx from '../../dist/cjs/Rx';
import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports

Expand Down Expand Up @@ -151,4 +152,21 @@ describe('Observable.prototype.single', () => {
expectObservable(e1.single(predicate)).toBe(expected, {z: undefined});
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});

it('should call predicate with indices starting at 0', () => {
const e1 = hot('--a--b--c--|');
const e1subs = '^ !';
const expected = '-----------(b|)';

let indices = [];
const predicate = function(value, index) {
indices.push(index);
return value === 'b';
};

expectObservable(e1.single(predicate).do(null, null, () => {
expect(indices).to.deep.equal([0, 1, 2]);
})).toBe(expected);
expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
13 changes: 6 additions & 7 deletions src/operator/single.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,19 +61,18 @@ class SingleSubscriber<T> extends Subscriber<T> {
}

protected _next(value: T): void {
const predicate = this.predicate;
this.index++;
if (predicate) {
this.tryNext(value);
const index = this.index++;

if (this.predicate) {
this.tryNext(value, index);
} else {
this.applySingleValue(value);
}
}

private tryNext(value: T): void {
private tryNext(value: T, index: number): void {
try {
const result = this.predicate(value, this.index, this.source);
if (result) {
if (this.predicate(value, index, this.source)) {
this.applySingleValue(value);
}
} catch (err) {
Expand Down

0 comments on commit c81882f

Please sign in to comment.