Skip to content

Commit

Permalink
Add index parameter to the predicate of Where
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin1994 committed May 9, 2021
1 parent 24a2c1b commit 457227e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
6 changes: 4 additions & 2 deletions template/implementationTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -703,11 +703,13 @@ abstract class EnumerableTemplate<T> extends AsyncEnumerable<T> {
yield* thatSet;
}

public async *where(predicate: (element: T) => AsyncOrSync<boolean>): WrapWithAsyncEnumerable<T> {
public async *where(predicate: (element: T, index: number) => AsyncOrSync<boolean>): WrapWithAsyncEnumerable<T> {
let i = 0;
for await (const element of this.iterable) {
if (await predicate(element)) {
if (await predicate(element, i)) {
yield element;
}
i++;
}
}

Expand Down
16 changes: 14 additions & 2 deletions tests/where.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ interface TestCase {
readonly name: string;
readonly input: Iterable<number>;
readonly output: Iterable<number>;
readonly predicate: (x: number) => boolean;
readonly predicate: (x: number, i: number) => boolean;
}

describe("LINQ", () => {
Expand All @@ -14,6 +14,18 @@ describe("LINQ", () => {
input: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
output: [0, 2, 4, 6, 8],
predicate: x => x % 2 === 0
},
{
name: "should filter the iterable with elements satisfying specified criteria using index",
input: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
output: [0, 2, 4],
predicate: (x, i) => x % 2 === 0 && i < 5
},
{
name: "should handle empty input",
input: [],
output: [],
predicate: x => x % 2 === 0
}
])("Where", ({name, input, output, predicate}) => {
it(`${name} synchronously`, () => {
Expand All @@ -25,7 +37,7 @@ describe("LINQ", () => {
});

it(`${name} asynchronously with asynchronous predicate`, async () => {
expect(await from(input).asAsync().where(x => Promise.resolve(predicate(x))).toArray()).toEqual(output);
expect(await from(input).asAsync().where((x, i) => Promise.resolve(predicate(x, i))).toArray()).toEqual(output);
});
});
});

0 comments on commit 457227e

Please sign in to comment.