Skip to content

Commit 71a3fd5

Browse files
committed
feat(asyncDropOnce): add asyncDropOnce function
1 parent 04f25e4 commit 71a3fd5

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

index.test.ts

Lines changed: 11 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+
asyncDropOnce,
45
asyncEmptyOnce,
56
asyncInitialOnce,
67
asyncIterator,
@@ -171,3 +172,13 @@ test("asyncTakeOnce", async t => {
171172
);
172173
t.deepEqual(await asyncToArrayOnce(asyncTakeOnce(asyncIterator([1, 2, 3, 4, 5]), 0)), []);
173174
});
175+
176+
test("asyncDropOnce", async t => {
177+
t.deepEqual(await asyncToArrayOnce(asyncDropOnce(asyncIterator([]), 3)), []);
178+
t.deepEqual(await asyncToArrayOnce(asyncDropOnce(asyncIterator([1, 2]), 3)), []);
179+
t.deepEqual(await asyncToArrayOnce(asyncDropOnce(asyncIterator([1, 2, 3, 4, 5]), 3)), [4, 5]);
180+
t.deepEqual(
181+
await asyncToArrayOnce(asyncDropOnce(asyncIterator([1, 2, 3, 4, 5]), 0)),
182+
[1, 2, 3, 4, 5]
183+
);
184+
});

index.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,3 +275,30 @@ export function asyncTakeOnceFn<T>(
275275
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
276276
return iterator => asyncTakeOnce(iterator, count);
277277
}
278+
279+
export function asyncDropOnce<T>(
280+
iterator: AsyncIteratorLike<T>,
281+
count: number | Promise<number>
282+
): AsyncIterator<T> {
283+
const it = asyncIterator(iterator);
284+
let i = 0;
285+
const before = async (): Promise<IteratorResult<T>> => {
286+
let element = await it.next();
287+
const c = await count;
288+
while (i++ < c && element.done !== true) {
289+
element = await it.next();
290+
}
291+
292+
next = during;
293+
return element;
294+
};
295+
const during = async (): Promise<IteratorResult<T>> => it.next();
296+
let next = before;
297+
return {next: async () => next()};
298+
}
299+
300+
export function asyncDropOnceFn<T>(
301+
count: number | Promise<number>
302+
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
303+
return iterator => asyncDropOnce(iterator, count);
304+
}

0 commit comments

Comments
 (0)