Skip to content

Commit cc3a587

Browse files
committed
feat(only): add only function
1 parent 62a0875 commit cc3a587

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

index.test.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import test from "ava";
2-
import {asyncIterable, initial, last, push, tail, toArray, unshift} from "./index";
2+
import {asyncIterable, initial, last, only, push, tail, toArray, unshift} from "./index";
33

44
test("tail", async t => {
55
t.deepEqual(await toArray(tail(asyncIterable([1, 2, 3, 4]))), [2, 3, 4]);
@@ -27,3 +27,9 @@ test("last", async t => {
2727
t.is(await last(asyncIterable([])), null);
2828
t.is(await last(asyncIterable([1, 2, 3])), 3);
2929
});
30+
31+
test("only", async t => {
32+
t.is(await only(asyncIterable([])), null);
33+
t.is(await only(asyncIterable([4])), 4);
34+
t.is(await only(asyncIterable([3, 4, 5])), null);
35+
});

index.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,12 @@ export async function last<T>(iterable: AsyncIterableLike<T>): Promise<T | null>
110110
}
111111

112112
export const asyncLast = last;
113+
114+
export async function only<T>(iterable: AsyncIterableLike<T>): Promise<T | null> {
115+
const iterator = asyncIterator(iterable);
116+
const first = await iterator.next();
117+
118+
return !(first.done ?? false) && ((await iterator.next()).done ?? false) ? first.value : null;
119+
}
120+
121+
export const asyncOnly = only;

0 commit comments

Comments
 (0)