Skip to content

Commit 5ebf905

Browse files
committed
feat(slice): add slice function
1 parent 102b432 commit 5ebf905

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

index.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import {
4545
removeFirst,
4646
scan,
4747
scan1,
48+
slice,
4849
sum,
4950
tail,
5051
take,
@@ -99,6 +100,14 @@ test("notEmpty", async t => {
99100
t.is(await notEmpty(asyncIterable([1, 2, 3])), true);
100101
});
101102

103+
test("slice", async t => {
104+
t.deepEqual(await toArray(slice(asyncIterable([1, 2, 3, 4]), 1)), [2, 3, 4]);
105+
t.deepEqual(await toArray(slice(asyncIterable([1, 2, 3, 4, 5]), 1, 4)), [2, 3, 4]);
106+
t.deepEqual(await toArray(slice(asyncIterable([1, 2, 3]), 2)), [3]);
107+
t.deepEqual(await toArray(slice(asyncIterable([1, 2, 3]), 0, 2)), [1, 2]);
108+
t.deepEqual(await toArray(slice(asyncIterable([]), 3, 5)), []);
109+
});
110+
102111
test("take", async t => {
103112
t.deepEqual(await toArray(take(asyncIterable([]), 3)), []);
104113
t.deepEqual(await toArray(take(asyncIterable([1, 2]), 3)), [1, 2]);

index.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,31 @@ export async function notEmpty(iterable: AsyncIterableLike<unknown>): Promise<bo
156156

157157
export const asyncNotEmpty = notEmpty;
158158

159+
export async function* slice<T>(
160+
iterable: AsyncIterableLike<T>,
161+
start: number | Promise<number> = 0,
162+
end: number | Promise<number> = Infinity
163+
): AsyncIterable<T> {
164+
const s = await start;
165+
const e = await end;
166+
167+
if (e === s) {
168+
return;
169+
}
170+
171+
const iterator = asyncIterator(iterable);
172+
let element = await iterator.next();
173+
174+
for (let i = 0; i < s && element.done !== true; ++i) {
175+
element = await iterator.next();
176+
}
177+
178+
for (let i = s; i < e && element.done !== true; ++i) {
179+
yield element.value;
180+
element = await iterator.next();
181+
}
182+
}
183+
159184
export async function* take<T>(
160185
iterable: AsyncIterableLike<T>,
161186
count: number | Promise<number>

0 commit comments

Comments
 (0)