Skip to content

Commit

Permalink
feat: add concurrent function to slice
Browse files Browse the repository at this point in the history
  • Loading branch information
ppeeou authored and DoHyeong Lee committed Dec 24, 2021
1 parent 0983a83 commit d6bba0a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/Lazy/slice.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import isNumber from "../isNumber";
import ReturnIterableIteratorType from "../types/ReturnIterableIteratorType";
import { isAsyncIterable, isIterable } from "../_internal/utils";
import concurrent, { isConcurrent } from "./concurrent";

function* sync<T>(
start = 0,
Expand All @@ -16,7 +17,7 @@ function* sync<T>(
}
}

async function* async<T>(
async function* asyncSequential<T>(
start = 0,
end = Infinity,
iterable: AsyncIterable<T>,
Expand All @@ -30,6 +31,30 @@ async function* async<T>(
}
}

function async<T>(
start = 0,
end = Infinity,
iterable: AsyncIterable<T>,
): AsyncIterableIterator<T> {
let iterator: AsyncIterator<T>;
return {
[Symbol.asyncIterator]() {
return this;
},

async next(_concurrent: any) {
if (iterator === undefined) {
// prettier-ignore
iterator = isConcurrent(_concurrent)
? asyncSequential(start, end, concurrent(_concurrent.length, iterable))
: asyncSequential(start, end, iterable);
}

return iterator.next(_concurrent);
},
};
}

function _slice<T extends Iterable<unknown> | AsyncIterable<unknown>>(
start: number,
end: number,
Expand Down
10 changes: 10 additions & 0 deletions test/Lazy/slice.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { pipe, slice, toArray, toAsync } from "../../src";
import { Concurrent } from "../../src/Lazy/concurrent";
import { generatorMock } from "../utils";

describe("slice", function () {
describe("sync", function () {
Expand Down Expand Up @@ -81,5 +83,13 @@ describe("slice", function () {
const res2 = await pipe([1, 2, 3, 4, 5], toAsync, slice(1, 3), toArray);
expect(res2).toEqual([2, 3]);
});

it("should be passed concurrent object when job works concurrently", async function () {
const mock = generatorMock();
const iter = slice(1, 2, mock);
const concurrent = Concurrent.of(2) as any;
await iter.next(concurrent);
expect((mock as any).getConcurrent()).toEqual(concurrent);
});
});
});

0 comments on commit d6bba0a

Please sign in to comment.