Skip to content

Commit bae7dd4

Browse files
committed
feat(asyncLastOnce): add asyncLastOnce function
1 parent ec2c41a commit bae7dd4

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

index.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import test from "ava";
33
import {
44
asyncInitialOnce,
55
asyncIterator,
6+
asyncLastOnce,
67
asyncPushOnce,
78
asyncTailOnce,
89
asyncToArrayOnce,
@@ -119,3 +120,8 @@ test("asyncInitialOnce", async t => {
119120
t.deepEqual(await asyncToArrayOnce(asyncInitialOnce(asyncIterator([1]))), []);
120121
t.deepEqual(await asyncToArrayOnce(asyncInitialOnce(asyncIterator([]))), []);
121122
});
123+
124+
test("asyncLastOnce", async t => {
125+
t.is(await asyncLastOnce(asyncIterator([])), null);
126+
t.is(await asyncLastOnce(asyncIterator([1, 2, 3])), 3);
127+
});

index.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,17 @@ export function asyncInitialOnce<T>(iterator: AsyncIteratorLike<T>): AsyncIterat
158158
}
159159
};
160160
}
161+
162+
export async function asyncLastOnce<T>(iterator: AsyncIteratorLike<T>): Promise<T | null> {
163+
const it = asyncIterator(iterator);
164+
let last = await it.next();
165+
if (last.done === true) {
166+
return null;
167+
}
168+
let element = await it.next();
169+
while (element.done !== true) {
170+
last = element;
171+
element = await it.next();
172+
}
173+
return last.value;
174+
}

0 commit comments

Comments
 (0)