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

fix(single): predicate function receives indices starting at 0 #2396

Merged
merged 1 commit into from
Feb 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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