Skip to content

Commit 17bec46

Browse files
committed
feat(asyncContainsOnce): add asyncContainsOnce function
1 parent 06776fd commit 17bec46

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
@@ -1,6 +1,7 @@
11
import type {ExecutionContext} from "ava";
22
import test from "ava";
33
import {
4+
asyncContainsOnce,
45
asyncDropOnce,
56
asyncDropUntilOnce,
67
asyncDropWhileOnce,
@@ -421,3 +422,8 @@ test("asyncIndexOnce", async t => {
421422
t.is(await asyncIndexOnce(asyncIterator([1, 2, 3, 4, 3, 2, 1]), 2), 3);
422423
t.is(await asyncIndexOnce(asyncIterator([1, 2, 3, 4, 3, 2, 1]), 7), null);
423424
});
425+
426+
test("asyncContainsOnce", async t => {
427+
t.true(await asyncContainsOnce(asyncIterator([1, 2, 3]), 1));
428+
t.false(await asyncContainsOnce(asyncIterator([1, 2, 3]), 0));
429+
});

index.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -701,3 +701,25 @@ export function asyncIndexOnceFn<T>(
701701
): (iterator: AsyncIteratorLike<T>) => Promise<T | null> {
702702
return async iterator => asyncIndexOnce(iterator, index);
703703
}
704+
705+
export async function asyncContainsOnce<T>(
706+
iterator: AsyncIteratorLike<T>,
707+
value: T | Promise<T>
708+
): Promise<boolean> {
709+
const it = asyncIterator(iterator);
710+
const [v, e] = await Promise.all([value, it.next()] as const);
711+
let element = e;
712+
while (element.done !== true) {
713+
if (element.value === v) {
714+
return true;
715+
}
716+
element = await it.next();
717+
}
718+
return false;
719+
}
720+
721+
export function asyncContainsOnceFn<T>(
722+
value: T | Promise<T>
723+
): (iterator: AsyncIteratorLike<T>) => Promise<boolean> {
724+
return async iterator => asyncContainsOnce(iterator, value);
725+
}

0 commit comments

Comments
 (0)