Skip to content

Commit a5de199

Browse files
committed
feat(index): add index function
1 parent 34d935b commit a5de199

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

index.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
filter,
1313
fold,
1414
fold1,
15+
index,
1516
indexOf,
1617
initial,
1718
last,
@@ -197,6 +198,11 @@ test("fold1", async t => {
197198
t.is(await fold1(asyncIterable([1, 2, 3]), (a, e, i) => a + e * i), 9);
198199
});
199200

201+
test("index", async t => {
202+
t.is(await index(asyncIterable([1, 2, 3, 4, 3, 2, 1]), 2), 3);
203+
t.is(await index(asyncIterable([1, 2, 3, 4, 3, 2, 1]), 7), null);
204+
});
205+
200206
test("contains", async t => {
201207
t.true(await contains(asyncIterable([1, 2, 3]), 1));
202208
t.false(await contains(asyncIterable([1, 2, 3]), 0));

index.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,28 @@ export function fold1Fn<T>(
578578

579579
export const asyncFold1Fn = fold1Fn;
580580

581+
export async function index<T>(iterable: AsyncIterableLike<T>, index: number): Promise<T | null> {
582+
if (index < 0 || !isFinite(index) || Math.floor(index) !== index) {
583+
throw new RangeError("illegal index");
584+
}
585+
586+
let i = 0;
587+
for await (const element of await iterable) {
588+
if (i++ === index) {
589+
return element;
590+
}
591+
}
592+
return null;
593+
}
594+
595+
export const asyncIndex = index;
596+
597+
export function indexFn<T>(index: number): (iterable: AsyncIterableLike<T>) => Promise<T | null> {
598+
return async iterable => asyncIndex(iterable, index);
599+
}
600+
601+
export const asyncIndexFn = indexFn;
602+
581603
export async function contains<T>(iterable: AsyncIterableLike<T>, value: T): Promise<boolean> {
582604
for await (const element of await iterable) {
583605
if (element === value) {

0 commit comments

Comments
 (0)