Skip to content

Commit 38116c6

Browse files
committed
feat(asyncDropWhileOnce): add asyncDropWhileOnce function
1 parent 5dcb827 commit 38116c6

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

index.test.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type {ExecutionContext} from "ava";
22
import test from "ava";
33
import {
44
asyncDropOnce,
5+
asyncDropWhileOnce,
56
asyncEmptyOnce,
67
asyncInitialOnce,
78
asyncIterator,
@@ -233,3 +234,25 @@ test("asyncTakeUntilOnce", async t => {
233234
[1, 2, 3]
234235
);
235236
});
237+
238+
test("asyncDropWhileOnce", async t => {
239+
t.deepEqual(await asyncToArrayOnce(asyncDropWhileOnce(asyncIterator([]), (_, i) => i < 3)), []);
240+
t.deepEqual(
241+
await asyncToArrayOnce(asyncDropWhileOnce(asyncIterator([1, 2]), (_, i) => i < 3)),
242+
[]
243+
);
244+
t.deepEqual(
245+
await asyncToArrayOnce(asyncDropWhileOnce(asyncIterator([1, 2, 3, 4, 5]), (_, i) => i < 3)),
246+
[4, 5]
247+
);
248+
t.deepEqual(
249+
await asyncToArrayOnce(asyncDropWhileOnce(asyncIterator([1, 2, 3, 4, 5]), () => false)),
250+
[1, 2, 3, 4, 5]
251+
);
252+
t.deepEqual(
253+
await asyncToArrayOnce(
254+
asyncDropWhileOnce(asyncIterator([1, 2, 3, 4, 3, 2, 1]), e => e < 4)
255+
),
256+
[4, 3, 2, 1]
257+
);
258+
});

index.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,3 +370,28 @@ export function asyncTakeUntilOnceFn<T>(
370370
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
371371
return iterator => asyncTakeUntilOnce(iterator, predicate);
372372
}
373+
374+
export function asyncDropWhileOnce<T>(
375+
iterator: AsyncIteratorLike<T>,
376+
predicate: (element: T, index: number) => boolean | Promise<boolean>
377+
): AsyncIterator<T> {
378+
const it = asyncIterator(iterator);
379+
let i = 0;
380+
const before = async (): Promise<IteratorResult<T>> => {
381+
let element = await it.next();
382+
while (element.done !== true && (await predicate(element.value, i++))) {
383+
element = await it.next();
384+
}
385+
next = during;
386+
return element;
387+
};
388+
const during = async (): Promise<IteratorResult<T>> => it.next();
389+
let next = before;
390+
return {next: async () => next()};
391+
}
392+
393+
export function asyncDropWhileOnceFn<T>(
394+
predicate: (element: T, index: number) => boolean | Promise<boolean>
395+
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
396+
return iterator => asyncDropWhileOnce(iterator, predicate);
397+
}

0 commit comments

Comments
 (0)