Skip to content

Commit 04f25e4

Browse files
committed
feat(asyncTakeOnce): add asyncTakeOnce function
1 parent 972a014 commit 04f25e4

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

index.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
asyncPushOnce,
1111
asyncSliceOnce,
1212
asyncTailOnce,
13+
asyncTakeOnce,
1314
asyncToArrayOnce,
1415
asyncUnshiftOnce
1516
} from "./index";
@@ -160,3 +161,13 @@ test("asyncSliceOnce", async t => {
160161
t.deepEqual(await asyncToArrayOnce(asyncSliceOnce(asyncIterator([1, 2, 3]), 2, 0)), []);
161162
t.deepEqual(await asyncToArrayOnce(asyncSliceOnce(asyncIterator([1, 2, 3]), 1, 1)), []);
162163
});
164+
165+
test("asyncTakeOnce", async t => {
166+
t.deepEqual(await asyncToArrayOnce(asyncTakeOnce(asyncIterator([]), 3)), []);
167+
t.deepEqual(await asyncToArrayOnce(asyncTakeOnce(asyncIterator([1, 2]), 3)), [1, 2]);
168+
t.deepEqual(
169+
await asyncToArrayOnce(asyncTakeOnce(asyncIterator([1, 2, 3, 4, 5]), 3)),
170+
[1, 2, 3]
171+
);
172+
t.deepEqual(await asyncToArrayOnce(asyncTakeOnce(asyncIterator([1, 2, 3, 4, 5]), 0)), []);
173+
});

index.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,3 +247,31 @@ export function asyncSliceOnceFn<T>(
247247
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
248248
return iterator => asyncSliceOnce(iterator, start, end);
249249
}
250+
251+
export function asyncTakeOnce<T>(
252+
iterator: AsyncIteratorLike<T>,
253+
count: number | Promise<number>
254+
): AsyncIterator<T> {
255+
const it = asyncIterator(iterator);
256+
let i = 0;
257+
const done: IteratorResult<T> = {done: true, value: undefined};
258+
const during = async (): Promise<IteratorResult<T>> => {
259+
const element = await it.next();
260+
const c = await count;
261+
if (i++ < c && element.done !== true) {
262+
return element;
263+
} else {
264+
next = after;
265+
return done;
266+
}
267+
};
268+
const after = async (): Promise<IteratorResult<T>> => done;
269+
let next = during;
270+
return {next: async () => next()};
271+
}
272+
273+
export function asyncTakeOnceFn<T>(
274+
count: number | Promise<number>
275+
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
276+
return iterator => asyncTakeOnce(iterator, count);
277+
}

0 commit comments

Comments
 (0)