Skip to content

Commit 9195637

Browse files
committed
feat(asyncIndexOfOnce): add asyncIndexOfOnce function
1 parent 17bec46 commit 9195637

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
@@ -13,6 +13,7 @@ import {
1313
asyncFilterOnce,
1414
asyncFold1Once,
1515
asyncFoldOnce,
16+
asyncIndexOfOnce,
1617
asyncIndexOnce,
1718
asyncInitialOnce,
1819
asyncIterator,
@@ -427,3 +428,8 @@ test("asyncContainsOnce", async t => {
427428
t.true(await asyncContainsOnce(asyncIterator([1, 2, 3]), 1));
428429
t.false(await asyncContainsOnce(asyncIterator([1, 2, 3]), 0));
429430
});
431+
432+
test("asyncIndexOfOnce", async t => {
433+
t.is(await asyncIndexOfOnce(asyncIterator([1, 2, 3, 4, 3, 2, 1]), 3), 2);
434+
t.is(await asyncIndexOfOnce(asyncIterator([1, 2, 3, 4, 3, 2, 1]), 5), null);
435+
});

index.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -723,3 +723,25 @@ export function asyncContainsOnceFn<T>(
723723
): (iterator: AsyncIteratorLike<T>) => Promise<boolean> {
724724
return async iterator => asyncContainsOnce(iterator, value);
725725
}
726+
727+
export async function asyncIndexOfOnce<T>(
728+
iterator: AsyncIteratorLike<T>,
729+
value: T | Promise<T>
730+
): Promise<number | null> {
731+
const it = asyncIterator(iterator);
732+
const [v, e] = await Promise.all([value, it.next()] as const);
733+
let element = e;
734+
for (let i = 0; element.done !== true; ++i) {
735+
if (element.value === v) {
736+
return i;
737+
}
738+
element = await it.next();
739+
}
740+
return null;
741+
}
742+
743+
export function asyncIndexOfOnceFn<T>(
744+
value: T | Promise<T>
745+
): (iterator: AsyncIteratorLike<T>) => Promise<number | null> {
746+
return async iterator => asyncIndexOfOnce(iterator, value);
747+
}

0 commit comments

Comments
 (0)