From d6bba0aa5e10c568adb1cd9fc9b3fd3286b7fac2 Mon Sep 17 00:00:00 2001 From: "hyunwoo.jo" Date: Thu, 23 Dec 2021 17:47:58 +0900 Subject: [PATCH] feat: add concurrent function to `slice` --- src/Lazy/slice.ts | 27 ++++++++++++++++++++++++++- test/Lazy/slice.spec.ts | 10 ++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/Lazy/slice.ts b/src/Lazy/slice.ts index ac7eb993..862e954d 100644 --- a/src/Lazy/slice.ts +++ b/src/Lazy/slice.ts @@ -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( start = 0, @@ -16,7 +17,7 @@ function* sync( } } -async function* async( +async function* asyncSequential( start = 0, end = Infinity, iterable: AsyncIterable, @@ -30,6 +31,30 @@ async function* async( } } +function async( + start = 0, + end = Infinity, + iterable: AsyncIterable, +): AsyncIterableIterator { + let iterator: AsyncIterator; + 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 | AsyncIterable>( start: number, end: number, diff --git a/test/Lazy/slice.spec.ts b/test/Lazy/slice.spec.ts index aceb212e..a6023bae 100644 --- a/test/Lazy/slice.spec.ts +++ b/test/Lazy/slice.spec.ts @@ -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 () { @@ -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); + }); }); });