Skip to content

Commit c81882f

Browse files
martinsikbenlesh
authored andcommitted
fix(single): predicate function receives indicies starting at 0 (#2396)
If the user is relying on indicies starting at 1 than this could be a BC. Otherwise now it's compatible with RxJS 4.
1 parent b9f611a commit c81882f

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

spec/operators/single-spec.ts

+18
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import {expect} from 'chai';
12
import * as Rx from '../../dist/cjs/Rx';
23
import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports
34

@@ -151,4 +152,21 @@ describe('Observable.prototype.single', () => {
151152
expectObservable(e1.single(predicate)).toBe(expected, {z: undefined});
152153
expectSubscriptions(e1.subscriptions).toBe(e1subs);
153154
});
155+
156+
it('should call predicate with indices starting at 0', () => {
157+
const e1 = hot('--a--b--c--|');
158+
const e1subs = '^ !';
159+
const expected = '-----------(b|)';
160+
161+
let indices = [];
162+
const predicate = function(value, index) {
163+
indices.push(index);
164+
return value === 'b';
165+
};
166+
167+
expectObservable(e1.single(predicate).do(null, null, () => {
168+
expect(indices).to.deep.equal([0, 1, 2]);
169+
})).toBe(expected);
170+
expectSubscriptions(e1.subscriptions).toBe(e1subs);
171+
});
154172
});

src/operator/single.ts

+6-7
Original file line numberDiff line numberDiff line change
@@ -61,19 +61,18 @@ class SingleSubscriber<T> extends Subscriber<T> {
6161
}
6262

6363
protected _next(value: T): void {
64-
const predicate = this.predicate;
65-
this.index++;
66-
if (predicate) {
67-
this.tryNext(value);
64+
const index = this.index++;
65+
66+
if (this.predicate) {
67+
this.tryNext(value, index);
6868
} else {
6969
this.applySingleValue(value);
7070
}
7171
}
7272

73-
private tryNext(value: T): void {
73+
private tryNext(value: T, index: number): void {
7474
try {
75-
const result = this.predicate(value, this.index, this.source);
76-
if (result) {
75+
if (this.predicate(value, index, this.source)) {
7776
this.applySingleValue(value);
7877
}
7978
} catch (err) {

0 commit comments

Comments
 (0)