Skip to content

Commit a36706f

Browse files
committed
feat(asyncPushOnce): add asyncPushOnce function
1 parent d316d31 commit a36706f

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

index.test.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type {ExecutionContext} from "ava";
22
import test from "ava";
3-
import {asyncIterator, asyncTailOnce, asyncToArrayOnce} from "./index";
3+
import {asyncIterator, asyncPushOnce, asyncTailOnce, asyncToArrayOnce} from "./index";
44

55
test("asyncIterator(empty)", async t => {
66
t.true((await asyncIterator([]).next()).done);
@@ -93,3 +93,8 @@ test("asyncTailOnce", async t => {
9393
t.deepEqual(await asyncToArrayOnce(asyncTailOnce(asyncIterator([1]))), []);
9494
t.deepEqual(await asyncToArrayOnce(asyncTailOnce(asyncIterator([]))), []);
9595
});
96+
97+
test("asyncPushOnce", async t => {
98+
t.deepEqual(await asyncToArrayOnce(asyncPushOnce(asyncIterator([1, 2, 3]), 4)), [1, 2, 3, 4]);
99+
t.deepEqual(await asyncToArrayOnce(asyncPushOnce(asyncIterator([]), 4)), [4]);
100+
});

index.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,26 @@ export function asyncTailOnce<T>(iterator: AsyncIteratorLike<T>): AsyncIterator<
102102
const tail = it.next().then(() => it);
103103
return fromPromiseOfIteratorLike(tail);
104104
}
105+
106+
export function asyncPushOnce<T>(
107+
iterator: AsyncIteratorLike<T>,
108+
value: T | Promise<T>
109+
): AsyncIterator<T> {
110+
const it = asyncIterator(iterator);
111+
let next = async (): Promise<IteratorResult<T>> => {
112+
const element = await it.next();
113+
if (element.done === true) {
114+
next = async () => Promise.resolve({done: true, value: undefined});
115+
return {value: await value};
116+
} else {
117+
return element;
118+
}
119+
};
120+
return {next: async () => next()};
121+
}
122+
123+
export function asyncPushOnceFn<T>(
124+
value: T | Promise<T>
125+
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
126+
return iterator => asyncPushOnce(iterator, value);
127+
}

0 commit comments

Comments
 (0)