From 790a76cbc725d7b7e780738c5feee924233fcc74 Mon Sep 17 00:00:00 2001 From: yousif-khalil-abdulkarim <118832973+yousif-khalil-abdulkarim@users.noreply.github.com> Date: Tue, 24 Dec 2024 11:52:37 +0100 Subject: [PATCH] Minor changes that doesn't effect Collection module (#52) * Removed unnecessary try catch that hindered unknown error to propagate up in ListCollection, IterableCollection and AsyncIterableCollection. I made AsyncIterableCollection return LazyPromise, abortableIterable, timeoutIterable and made it use TimeSpan class. I made AsyncCollection contract use PromiseLike instead of Promise type. * Renamed the timeout method to takeUntilTimeout and abort method to takeUntilAbort of IAsyncCollection contract * Added changeset file --- .changeset/curvy-ligers-rule.md | 9 + src/_shared/types.ts | 4 +- src/async/_module.ts | 1 + .../_shared/_module.ts | 4 +- .../_shared/async-abort-iterable.ts | 25 - .../_shared/async-chunk-iterable.ts | 46 +- .../_shared/async-chunk-while-iterable.ts | 42 +- .../_shared/async-collapse-iterable.ts | 24 +- .../_shared/async-count-by-iterable.ts | 30 +- .../_shared/async-cross-join-iterable.ts | 84 +- .../_shared/async-delay-iterable.ts | 26 - .../_shared/async-error-handler-iterable.ts | 27 + .../_shared/async-filter-iterable.ts | 18 +- .../_shared/async-flat-map-iterable.ts | 16 +- .../_shared/async-insert-after-iterable.ts | 34 +- .../_shared/async-insert-before-iterable.ts | 34 +- .../_shared/async-map-iterable.ts | 16 +- .../_shared/async-merge-iterable.ts | 19 +- .../_shared/async-partion-iterable.ts | 30 +- .../_shared/async-repeat-iterable.ts | 24 +- .../_shared/async-skip-iterable.ts | 24 +- .../_shared/async-skip-until-iterable.ts | 36 +- .../_shared/async-sliding-iterable.ts | 36 +- .../_shared/async-split-iterable.ts | 56 +- .../_shared/async-take-iterable.ts | 24 +- .../_shared/async-take-until-iterable.ts | 20 +- .../_shared/async-tap-iterable.ts | 16 +- .../_shared/async-timeout-iterable.ts | 20 - .../_shared/async-unique-iterable.ts | 24 +- .../_shared/async-update-iterable.ts | 26 +- .../_shared/async-when-iterable.ts | 22 +- .../async-iterable-collection.ts | 567 +++--- .../_shared/chunk-iterable.ts | 46 +- .../_shared/chunk-while-iterable.ts | 38 +- .../_shared/collapse-iterable.ts | 24 +- .../_shared/count-by-iterable.ts | 35 +- .../_shared/cross-join-iterable.ts | 77 +- .../_shared/entries-iterable.ts | 23 +- .../_shared/filter-iterable.ts | 18 +- .../_shared/flat-map-iterable.ts | 21 +- .../_shared/group-by-iterable.ts | 39 +- .../_shared/insert-after-iterable.ts | 27 +- .../_shared/insert-before-iterable.ts | 27 +- .../_shared/map-iterable.ts | 21 +- .../_shared/merge-iterable.ts | 19 +- .../_shared/pad-end-iterable.ts | 44 +- .../_shared/pad-start-iterable.ts | 44 +- .../_shared/partion-iterable.ts | 30 +- .../_shared/repeat-iterable.ts | 24 +- .../_shared/reverse-iterable.ts | 28 +- .../_shared/shuffle-iterable.ts | 33 +- .../_shared/skip-iterable.ts | 24 +- .../_shared/skip-until-iterable.ts | 24 +- .../_shared/slice-iterable.ts | 48 +- .../_shared/sliding-iterable.ts | 36 +- .../_shared/sort-iterable.ts | 18 +- .../_shared/split-iterable.ts | 56 +- .../_shared/take-iterable.ts | 24 +- .../_shared/take-until-iterable.ts | 20 +- .../_shared/tap-iterable.ts | 21 +- .../_shared/unique-iterable.ts | 29 +- .../_shared/update-iterable.ts | 26 +- .../_shared/when-iterable.ts | 20 +- .../_shared/zip-iterable.ts | 33 +- .../iterable-collection.ts | 621 ++----- .../list-collection/list-collection.ts | 1629 +++++------------ src/contracts/collection/_shared.ts | 16 +- .../collection/async-collection.contract.ts | 96 +- 68 files changed, 1432 insertions(+), 3311 deletions(-) create mode 100644 .changeset/curvy-ligers-rule.md delete mode 100644 src/collection/async-iterable-collection/_shared/async-abort-iterable.ts delete mode 100644 src/collection/async-iterable-collection/_shared/async-delay-iterable.ts create mode 100644 src/collection/async-iterable-collection/_shared/async-error-handler-iterable.ts delete mode 100644 src/collection/async-iterable-collection/_shared/async-timeout-iterable.ts diff --git a/.changeset/curvy-ligers-rule.md b/.changeset/curvy-ligers-rule.md new file mode 100644 index 00000000..6dea8dfd --- /dev/null +++ b/.changeset/curvy-ligers-rule.md @@ -0,0 +1,9 @@ +--- +"@daiso-tech/core": minor +--- + +# IAsyncCollection and AsyncIterableCollection +Changed IAsyncCollection contract to use PromiseLike instead of Promise. +Changed AsyncIterableCollection to use LazyPromise instead of Promise. +Removed all try catches catched unknown errors. +Renamed timeout to takeUntilTimeout, and abort to takeUntilAbort. \ No newline at end of file diff --git a/src/_shared/types.ts b/src/_shared/types.ts index 83d20363..25f180b4 100644 --- a/src/_shared/types.ts +++ b/src/_shared/types.ts @@ -8,7 +8,7 @@ export type EnsureType = export type RecordItem = [key: TKey, value: TValue]; export type Lazyable = TValue | (() => TValue); -export type Promisable = TValue | Promise; +export type Promisable = TValue | PromiseLike; export type AsyncLazyable = TValue | (() => Promisable); export type AsyncIterableValue = @@ -18,7 +18,7 @@ export type AsyncIterableValue = export type AnyFunction = (...parameters: unknown[]) => unknown; export type IInitizable = { - init(): Promise; + init(): PromiseLike; }; export type Func = ( ...args_: TArgs diff --git a/src/async/_module.ts b/src/async/_module.ts index 6893ffa5..08dbea66 100644 --- a/src/async/_module.ts +++ b/src/async/_module.ts @@ -1,3 +1,4 @@ +export * from "@/async/_shared"; export * from "@/async/abortable/_module"; export * from "@/async/abortable-iterable/_module"; export * from "@/async/backof-policies/_module"; diff --git a/src/collection/async-iterable-collection/_shared/_module.ts b/src/collection/async-iterable-collection/_shared/_module.ts index 22ddd65e..29b76860 100644 --- a/src/collection/async-iterable-collection/_shared/_module.ts +++ b/src/collection/async-iterable-collection/_shared/_module.ts @@ -4,6 +4,7 @@ export * from "@/collection/async-iterable-collection/_shared/async-collapse-ite export * from "@/collection/async-iterable-collection/_shared/async-count-by-iterable"; export * from "@/collection/async-iterable-collection/_shared/async-cross-join-iterable"; export * from "@/collection/async-iterable-collection/_shared/async-entries-iterable"; +export * from "@/collection/async-iterable-collection/_shared/async-error-handler-iterable"; export * from "@/collection/async-iterable-collection/_shared/async-filter-iterable"; export * from "@/collection/async-iterable-collection/_shared/async-flat-map-iterable"; export * from "@/collection/async-iterable-collection/_shared/async-group-by-iterable"; @@ -30,6 +31,3 @@ export * from "@/collection/async-iterable-collection/_shared/async-unique-itera export * from "@/collection/async-iterable-collection/_shared/async-update-iterable"; export * from "@/collection/async-iterable-collection/_shared/async-when-iterable"; export * from "@/collection/async-iterable-collection/_shared/async-zip-iterable"; -export * from "@/collection/async-iterable-collection/_shared/async-timeout-iterable"; -export * from "@/collection/async-iterable-collection/_shared/async-delay-iterable"; -export * from "@/collection/async-iterable-collection/_shared/async-abort-iterable"; diff --git a/src/collection/async-iterable-collection/_shared/async-abort-iterable.ts b/src/collection/async-iterable-collection/_shared/async-abort-iterable.ts deleted file mode 100644 index 92e4d955..00000000 --- a/src/collection/async-iterable-collection/_shared/async-abort-iterable.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { type IAsyncCollection } from "@/contracts/collection/_module"; - -/** - * @internal - */ -export class AsyncAbortIterable implements AsyncIterable { - constructor( - private collection: IAsyncCollection, - private signal: AbortSignal, - ) {} - - async *[Symbol.asyncIterator](): AsyncIterator { - let hasAborted = false; - this.signal.addEventListener("abort", () => { - hasAborted = true; - }); - for await (const item of this.collection) { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (hasAborted) { - break; - } - yield item; - } - } -} diff --git a/src/collection/async-iterable-collection/_shared/async-chunk-iterable.ts b/src/collection/async-iterable-collection/_shared/async-chunk-iterable.ts index f54f6114..5e8dddf9 100644 --- a/src/collection/async-iterable-collection/_shared/async-chunk-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-chunk-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type IAsyncCollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type IAsyncCollection } from "@/contracts/collection/_module"; import { type AsyncIterableValue } from "@/_shared/types"; /** @@ -20,33 +16,23 @@ export class AsyncChunkIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator> { - try { - const array: TInput[] = []; - let currentChunkSize = 0; - let isFirstIteration = true; - for await (const item of this.collection) { - currentChunkSize %= this.chunkSize; - const isFilled = currentChunkSize === 0; - if (!isFirstIteration && isFilled) { - yield this.makeCollection(array); - array.length = 0; - } - array.push(item); - currentChunkSize++; - isFirstIteration = false; - } - const hasRest = currentChunkSize !== 0; - if (hasRest) { + const array: TInput[] = []; + let currentChunkSize = 0; + let isFirstIteration = true; + for await (const item of this.collection) { + currentChunkSize %= this.chunkSize; + const isFilled = currentChunkSize === 0; + if (!isFirstIteration && isFilled) { yield this.makeCollection(array); + array.length = 0; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + array.push(item); + currentChunkSize++; + isFirstIteration = false; + } + const hasRest = currentChunkSize !== 0; + if (hasRest) { + yield this.makeCollection(array); } } } diff --git a/src/collection/async-iterable-collection/_shared/async-chunk-while-iterable.ts b/src/collection/async-iterable-collection/_shared/async-chunk-while-iterable.ts index 5f42b595..5afde21d 100644 --- a/src/collection/async-iterable-collection/_shared/async-chunk-while-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-chunk-while-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncPredicate, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; import { type AsyncIterableValue } from "@/_shared/types"; @@ -22,34 +20,20 @@ export class AsyncChunkWhileIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator> { - try { - const array: TInput[] = []; - for await (const [index, item] of this.collection.entries()) { - if (index === 0) { - array.push(item); - } else if ( - await this.predicateFn( - item, - index, - this.makeCollection(array), - ) - ) { - array.push(item); - } else { - yield this.makeCollection(array); - array.length = 0; - array.push(item); - } + const array: TInput[] = []; + for await (const [index, item] of this.collection.entries()) { + if (index === 0) { + array.push(item); + } else if ( + await this.predicateFn(item, index, this.makeCollection(array)) + ) { + array.push(item); + } else { + yield this.makeCollection(array); + array.length = 0; + array.push(item); } - yield this.makeCollection(array); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + yield this.makeCollection(array); } } diff --git a/src/collection/async-iterable-collection/_shared/async-collapse-iterable.ts b/src/collection/async-iterable-collection/_shared/async-collapse-iterable.ts index 242c716a..8c42011b 100644 --- a/src/collection/async-iterable-collection/_shared/async-collapse-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-collapse-iterable.ts @@ -1,9 +1,7 @@ import { isAsyncIterable, isIterable } from "@/collection/_shared"; import { type AsyncCollapse, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -15,23 +13,13 @@ export class AsyncCollapseIterable constructor(private collection: IAsyncCollection) {} async *[Symbol.asyncIterator](): AsyncIterator> { - try { - for await (const item of this.collection) { - if (isIterable(item) || isAsyncIterable(item)) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - yield* item as any; - } else { - yield item as AsyncCollapse; - } + for await (const item of this.collection) { + if (isIterable(item) || isAsyncIterable(item)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + yield* item as any; + } else { + yield item as AsyncCollapse; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/async-iterable-collection/_shared/async-count-by-iterable.ts b/src/collection/async-iterable-collection/_shared/async-count-by-iterable.ts index dfad53bc..83a99a65 100644 --- a/src/collection/async-iterable-collection/_shared/async-count-by-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-count-by-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncMap, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; import { type RecordItem } from "@/_shared/types"; /** @@ -25,27 +23,17 @@ export class AsyncCountByIterable async *[Symbol.asyncIterator](): AsyncIterator< RecordItem > { - try { - const map = new Map(); - for await (const [index, item] of this.collection.entries()) { - const key = await this.callback(item, index, this.collection); - if (!map.has(key)) { - map.set(key, 0); - } - const counter = map.get(key); - if (counter !== undefined) { - map.set(key, counter + 1); - } + const map = new Map(); + for await (const [index, item] of this.collection.entries()) { + const key = await this.callback(item, index, this.collection); + if (!map.has(key)) { + map.set(key, 0); } - yield* map; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const counter = map.get(key); + if (counter !== undefined) { + map.set(key, counter + 1); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + yield* map; } } diff --git a/src/collection/async-iterable-collection/_shared/async-cross-join-iterable.ts b/src/collection/async-iterable-collection/_shared/async-cross-join-iterable.ts index c765b1b7..0cc8a7f7 100644 --- a/src/collection/async-iterable-collection/_shared/async-cross-join-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-cross-join-iterable.ts @@ -1,9 +1,5 @@ import type { CrossJoinResult } from "@/contracts/collection/_module"; -import { - CollectionError, - type IAsyncCollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type IAsyncCollection } from "@/contracts/collection/_module"; import { type AsyncIterableValue } from "@/_shared/types"; import { isIterable } from "@/collection/_module"; @@ -24,52 +20,38 @@ export class AsyncCrossJoinIterable async *[Symbol.asyncIterator](): AsyncIterator< CrossJoinResult > { - try { - const combinations = ( - await this.makeCollection([ - this.collection, - this.makeCollection(this.iterable), - ] as IAsyncCollection[]).reduce< - IAsyncCollection> - >( - async (a, b) => { - return await a - .map((x) => { - return b.map((y) => { - return [...x, y]; - }); - }) - .reduce< - IAsyncCollection> - >( - (c, b) => c.append(b), - this.makeCollection>( - [], - ), - ); - }, - this.makeCollection([[] as Array]), - ) - ).map((combination) => { - // Flatting the array - return combination.reduce>((a, b) => { - return [...a, ...(isIterable(b) ? b : [b])] as Array< - TInput | TExtended - >; - }, []); - }); + const combinations = ( + await this.makeCollection([ + this.collection, + this.makeCollection(this.iterable), + ] as IAsyncCollection[]).reduce< + IAsyncCollection> + >( + async (a, b) => { + return await a + .map((x) => { + return b.map((y) => { + return [...x, y]; + }); + }) + .reduce>>( + (c, b) => c.append(b), + this.makeCollection>([]), + ); + }, + this.makeCollection([[] as Array]), + ) + ).map((combination) => { + // Flatting the array + return combination.reduce>((a, b) => { + return [...a, ...(isIterable(b) ? b : [b])] as Array< + TInput | TExtended + >; + }, []); + }); - yield* combinations as AsyncIterable< - CrossJoinResult - >; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + yield* combinations as AsyncIterable< + CrossJoinResult + >; } } diff --git a/src/collection/async-iterable-collection/_shared/async-delay-iterable.ts b/src/collection/async-iterable-collection/_shared/async-delay-iterable.ts deleted file mode 100644 index 8e19a370..00000000 --- a/src/collection/async-iterable-collection/_shared/async-delay-iterable.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { type IAsyncCollection } from "@/contracts/collection/_module"; - -/** - * @internal - */ -export class AsyncDelayIterable implements AsyncIterable { - constructor( - private collection: IAsyncCollection, - private timeInMs: number, - ) {} - - async *[Symbol.asyncIterator](): AsyncIterator { - let isFirstIteration = true; - for await (const item of this.collection) { - if (!isFirstIteration) { - await new Promise((resolve) => - setTimeout(resolve, this.timeInMs), - ); - } - if (isFirstIteration) { - isFirstIteration = false; - } - yield item; - } - } -} diff --git a/src/collection/async-iterable-collection/_shared/async-error-handler-iterable.ts b/src/collection/async-iterable-collection/_shared/async-error-handler-iterable.ts new file mode 100644 index 00000000..6419f8fd --- /dev/null +++ b/src/collection/async-iterable-collection/_shared/async-error-handler-iterable.ts @@ -0,0 +1,27 @@ +export class AsyncErrorHandlerIterable + implements AsyncIterable +{ + constructor( + private readonly iterable: AsyncIterable, + private readonly errorPasser: (error: unknown) => boolean, + ) {} + + async *[Symbol.asyncIterator](): AsyncIterator { + const iterator = this.iterable[Symbol.asyncIterator](); + try { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const result = await iterator.next(); + if (result.done) { + return; + } + yield result.value; + } + } catch (error: unknown) { + if (this.errorPasser(error)) { + return; + } + throw error; + } + } +} diff --git a/src/collection/async-iterable-collection/_shared/async-filter-iterable.ts b/src/collection/async-iterable-collection/_shared/async-filter-iterable.ts index 58c61cbc..af99769c 100644 --- a/src/collection/async-iterable-collection/_shared/async-filter-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-filter-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncPredicate, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -21,20 +19,10 @@ export class AsyncFilterIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - for await (const [index, item] of this.collection.entries()) { - if (await this.predicateFn(item, index, this.collection)) { - yield item as TOutput; - } + for await (const [index, item] of this.collection.entries()) { + if (await this.predicateFn(item, index, this.collection)) { + yield item as TOutput; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/async-iterable-collection/_shared/async-flat-map-iterable.ts b/src/collection/async-iterable-collection/_shared/async-flat-map-iterable.ts index 68fe544e..6ebe3019 100644 --- a/src/collection/async-iterable-collection/_shared/async-flat-map-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-flat-map-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncMap, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -21,18 +19,8 @@ export class AsyncFlatMapIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - for await (const [index, item] of this.collection.entries()) { - yield* await this.mapFn(item, index, this.collection); - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + for await (const [index, item] of this.collection.entries()) { + yield* await this.mapFn(item, index, this.collection); } } } diff --git a/src/collection/async-iterable-collection/_shared/async-insert-after-iterable.ts b/src/collection/async-iterable-collection/_shared/async-insert-after-iterable.ts index 23cb09e8..54d42872 100644 --- a/src/collection/async-iterable-collection/_shared/async-insert-after-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-insert-after-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncPredicate, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; import { type AsyncIterableValue } from "@/_shared/types"; @@ -19,28 +17,18 @@ export class AsyncInsertAfterIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - let hasMatched = false, - index = 0; - for await (const item of this.collection) { - yield item; - if ( - !hasMatched && - (await this.predicateFn(item, index, this.collection)) - ) { - yield* this.iterable; - hasMatched = true; - } - index++; + let hasMatched = false, + index = 0; + for await (const item of this.collection) { + yield item; + if ( + !hasMatched && + (await this.predicateFn(item, index, this.collection)) + ) { + yield* this.iterable; + hasMatched = true; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; } } } diff --git a/src/collection/async-iterable-collection/_shared/async-insert-before-iterable.ts b/src/collection/async-iterable-collection/_shared/async-insert-before-iterable.ts index ddeed1ea..e7127232 100644 --- a/src/collection/async-iterable-collection/_shared/async-insert-before-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-insert-before-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncPredicate, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; import { type AsyncIterableValue } from "@/_shared/types"; @@ -19,28 +17,18 @@ export class AsyncInsertBeforeIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - let hasMatched = false, - index = 0; - for await (const item of this.collection) { - if ( - !hasMatched && - (await this.predicateFn(item, index, this.collection)) - ) { - yield* this.iterable; - hasMatched = true; - } - yield item; - index++; + let hasMatched = false, + index = 0; + for await (const item of this.collection) { + if ( + !hasMatched && + (await this.predicateFn(item, index, this.collection)) + ) { + yield* this.iterable; + hasMatched = true; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + yield item; + index++; } } } diff --git a/src/collection/async-iterable-collection/_shared/async-map-iterable.ts b/src/collection/async-iterable-collection/_shared/async-map-iterable.ts index 4c2f02db..963f3828 100644 --- a/src/collection/async-iterable-collection/_shared/async-map-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-map-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncMap, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -17,18 +15,8 @@ export class AsyncMapIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - for await (const [index, item] of this.collection.entries()) { - yield this.mapFn(item, index, this.collection); - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + for await (const [index, item] of this.collection.entries()) { + yield this.mapFn(item, index, this.collection); } } } diff --git a/src/collection/async-iterable-collection/_shared/async-merge-iterable.ts b/src/collection/async-iterable-collection/_shared/async-merge-iterable.ts index 7a795ceb..d0071774 100644 --- a/src/collection/async-iterable-collection/_shared/async-merge-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-merge-iterable.ts @@ -1,7 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import {} from "@/contracts/collection/_module"; import { type AsyncIterableValue } from "@/_shared/types"; /** @@ -16,17 +13,7 @@ export class AsyncMergeIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - yield* this.iterableA; - yield* this.iterableB; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + yield* this.iterableA; + yield* this.iterableB; } } diff --git a/src/collection/async-iterable-collection/_shared/async-partion-iterable.ts b/src/collection/async-iterable-collection/_shared/async-partion-iterable.ts index 41c73ac2..985bbfe0 100644 --- a/src/collection/async-iterable-collection/_shared/async-partion-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-partion-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncPredicate, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; import { type AsyncIterableValue } from "@/_shared/types"; @@ -21,26 +19,16 @@ export class AsyncPartionIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator> { - try { - const arrayA: TInput[] = []; - const arrayB: TInput[] = []; - for await (const [index, item] of this.collection.entries()) { - if (await this.predicateFn(item, index, this.collection)) { - arrayA.push(item); - } else { - arrayB.push(item); - } + const arrayA: TInput[] = []; + const arrayB: TInput[] = []; + for await (const [index, item] of this.collection.entries()) { + if (await this.predicateFn(item, index, this.collection)) { + arrayA.push(item); + } else { + arrayB.push(item); } - yield this.makeCollection(arrayA); - yield this.makeCollection(arrayB); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + yield this.makeCollection(arrayA); + yield this.makeCollection(arrayB); } } diff --git a/src/collection/async-iterable-collection/_shared/async-repeat-iterable.ts b/src/collection/async-iterable-collection/_shared/async-repeat-iterable.ts index 6464118b..fefe3fde 100644 --- a/src/collection/async-iterable-collection/_shared/async-repeat-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-repeat-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type IAsyncCollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type IAsyncCollection } from "@/contracts/collection/_module"; import { type AsyncIterableValue } from "@/_shared/types"; /** @@ -18,20 +14,10 @@ export class AsyncRepeatIterable implements AsyncIterable { ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - let collection = this.makeAsyncCollection([]); - for (let index = 0; index < this.amount; index++) { - collection = collection.append(this.collection); - } - yield* collection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + let collection = this.makeAsyncCollection([]); + for (let index = 0; index < this.amount; index++) { + collection = collection.append(this.collection); } + yield* collection; } } diff --git a/src/collection/async-iterable-collection/_shared/async-skip-iterable.ts b/src/collection/async-iterable-collection/_shared/async-skip-iterable.ts index 01bafd38..904dde95 100644 --- a/src/collection/async-iterable-collection/_shared/async-skip-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-skip-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type IAsyncCollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type IAsyncCollection } from "@/contracts/collection/_module"; /** * @internal @@ -14,21 +10,9 @@ export class AsyncSkipIterable implements AsyncIterable { ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - if (this.limit < 0) { - this.limit = (await this.collection.size()) + this.limit; - } - yield* this.collection.skipWhile( - (_item, index) => index < this.limit, - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + if (this.limit < 0) { + this.limit = (await this.collection.size()) + this.limit; } + yield* this.collection.skipWhile((_item, index) => index < this.limit); } } diff --git a/src/collection/async-iterable-collection/_shared/async-skip-until-iterable.ts b/src/collection/async-iterable-collection/_shared/async-skip-until-iterable.ts index 2195100e..ba41d782 100644 --- a/src/collection/async-iterable-collection/_shared/async-skip-until-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-skip-until-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncPredicate, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -15,30 +13,20 @@ export class AsyncSkipUntilIterable implements AsyncIterable { ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - let hasMatched = false, - index = 0; - for await (const item of this.collection) { - if (!hasMatched) { - hasMatched = await this.predicateFn( - item, - index, - this.collection, - ); - } - if (hasMatched) { - yield item; - } - index++; + let hasMatched = false, + index = 0; + for await (const item of this.collection) { + if (!hasMatched) { + hasMatched = await this.predicateFn( + item, + index, + this.collection, + ); } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (hasMatched) { + yield item; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; } } } diff --git a/src/collection/async-iterable-collection/_shared/async-sliding-iterable.ts b/src/collection/async-iterable-collection/_shared/async-sliding-iterable.ts index 4da8e214..5efd3a58 100644 --- a/src/collection/async-iterable-collection/_shared/async-sliding-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-sliding-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type IAsyncCollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type IAsyncCollection } from "@/contracts/collection/_module"; /** * @internal @@ -17,30 +13,20 @@ export class AsyncSlidingIteralbe ) {} async *[Symbol.asyncIterator](): AsyncIterator> { - try { - if (this.step <= 0) { - return; - } - const size = await this.collection.size(); + if (this.step <= 0) { + return; + } + const size = await this.collection.size(); - for (let index = 0; index < size; index += this.step) { - const start = index; - const end = index + this.chunkSize; + for (let index = 0; index < size; index += this.step) { + const start = index; + const end = index + this.chunkSize; - yield this.collection.slice(start, end); + yield this.collection.slice(start, end); - if (end >= size) { - break; - } - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (end >= size) { + break; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/async-iterable-collection/_shared/async-split-iterable.ts b/src/collection/async-iterable-collection/_shared/async-split-iterable.ts index 6d5170a1..e71da294 100644 --- a/src/collection/async-iterable-collection/_shared/async-split-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-split-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type IAsyncCollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type IAsyncCollection } from "@/contracts/collection/_module"; import { type AsyncIterableValue } from "@/_shared/types"; /** @@ -21,41 +17,31 @@ export class AsyncSplitIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator> { - try { - const size = await this.collection.size(), - minChunkSize = Math.floor(size / this.chunkAmount), - restSize = size % this.chunkAmount, - chunkSizes = Array.from({ - length: this.chunkAmount, - }).fill(minChunkSize); + const size = await this.collection.size(), + minChunkSize = Math.floor(size / this.chunkAmount), + restSize = size % this.chunkAmount, + chunkSizes = Array.from({ + length: this.chunkAmount, + }).fill(minChunkSize); - for (let i = 1; i <= restSize; i++) { - const chunkIndex = (i - 1) % this.chunkAmount; - if (chunkSizes[chunkIndex]) { - chunkSizes[chunkIndex] = chunkSizes[chunkIndex] + 1; - } + for (let i = 1; i <= restSize; i++) { + const chunkIndex = (i - 1) % this.chunkAmount; + if (chunkSizes[chunkIndex]) { + chunkSizes[chunkIndex] = chunkSizes[chunkIndex] + 1; } + } - const iterator = this.collection.toIterator(); - const array: TInput[] = []; - for (const chunkSize of chunkSizes) { - for (let i = 0; i < chunkSize; i++) { - const item = await iterator.next(); - if (item.value !== undefined) { - array.push(item.value); - } + const iterator = this.collection.toIterator(); + const array: TInput[] = []; + for (const chunkSize of chunkSizes) { + for (let i = 0; i < chunkSize; i++) { + const item = await iterator.next(); + if (item.value !== undefined) { + array.push(item.value); } - yield this.makeCollection(array); - array.length = 0; - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + yield this.makeCollection(array); + array.length = 0; } } } diff --git a/src/collection/async-iterable-collection/_shared/async-take-iterable.ts b/src/collection/async-iterable-collection/_shared/async-take-iterable.ts index 2ea39120..c291d033 100644 --- a/src/collection/async-iterable-collection/_shared/async-take-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-take-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type IAsyncCollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type IAsyncCollection } from "@/contracts/collection/_module"; /** * @internal @@ -14,21 +10,9 @@ export class AsyncTakeIterable implements AsyncIterable { ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - if (this.limit < 0) { - this.limit = (await this.collection.size()) + this.limit; - } - yield* this.collection.takeWhile( - (_item, index) => index < this.limit, - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + if (this.limit < 0) { + this.limit = (await this.collection.size()) + this.limit; } + yield* this.collection.takeWhile((_item, index) => index < this.limit); } } diff --git a/src/collection/async-iterable-collection/_shared/async-take-until-iterable.ts b/src/collection/async-iterable-collection/_shared/async-take-until-iterable.ts index 4bfe533c..4358ae77 100644 --- a/src/collection/async-iterable-collection/_shared/async-take-until-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-take-until-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncPredicate, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -15,21 +13,11 @@ export class AsyncTakeUntilIterable implements AsyncIterable { ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - for await (const [index, item] of this.collection.entries()) { - if (await this.predicateFn(item, index, this.collection)) { - break; - } - yield item; + for await (const [index, item] of this.collection.entries()) { + if (await this.predicateFn(item, index, this.collection)) { + break; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + yield item; } } } diff --git a/src/collection/async-iterable-collection/_shared/async-tap-iterable.ts b/src/collection/async-iterable-collection/_shared/async-tap-iterable.ts index 8193d0f8..e136c81b 100644 --- a/src/collection/async-iterable-collection/_shared/async-tap-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-tap-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncTap, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -15,17 +13,7 @@ export class AsyncTapIterable implements AsyncIterable { ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - await this.callback(this.collection); - yield* this.collection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + await this.callback(this.collection); + yield* this.collection; } } diff --git a/src/collection/async-iterable-collection/_shared/async-timeout-iterable.ts b/src/collection/async-iterable-collection/_shared/async-timeout-iterable.ts deleted file mode 100644 index 0532bf82..00000000 --- a/src/collection/async-iterable-collection/_shared/async-timeout-iterable.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { type IAsyncCollection } from "@/contracts/collection/_module"; - -/** - * @internal - */ -export class AsyncTimeoutIterable implements AsyncIterable { - constructor( - private collection: IAsyncCollection, - private timeInMs: number, - ) {} - - async *[Symbol.asyncIterator](): AsyncIterator { - const abortController = new AbortController(); - const timeout = setTimeout(() => { - abortController.abort(); - }, this.timeInMs); - yield* this.collection.abort(abortController.signal); - clearTimeout(timeout); - } -} diff --git a/src/collection/async-iterable-collection/_shared/async-unique-iterable.ts b/src/collection/async-iterable-collection/_shared/async-unique-iterable.ts index 71ac57ed..a24f5077 100644 --- a/src/collection/async-iterable-collection/_shared/async-unique-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-unique-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncMap, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -23,23 +21,13 @@ export class AsyncUniqueIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - const set = new Set([]); - for await (const [index, item] of this.collection.entries()) { - const item_ = await this.callback(item, index, this.collection); - if (!set.has(item_)) { - yield item; - } - set.add(item_); + const set = new Set([]); + for await (const [index, item] of this.collection.entries()) { + const item_ = await this.callback(item, index, this.collection); + if (!set.has(item_)) { + yield item; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + set.add(item_); } } } diff --git a/src/collection/async-iterable-collection/_shared/async-update-iterable.ts b/src/collection/async-iterable-collection/_shared/async-update-iterable.ts index 9440eeb4..812d4fd3 100644 --- a/src/collection/async-iterable-collection/_shared/async-update-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-update-iterable.ts @@ -1,9 +1,7 @@ import { type AsyncPredicate, type AsyncMap, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, type ChangendItem, } from "@/contracts/collection/_module"; @@ -33,26 +31,12 @@ export class AsyncUpdateIterable< async *[Symbol.asyncIterator](): AsyncIterator< ChangendItem > { - try { - for await (const [index, item] of this.collection.entries()) { - if (await this.predicateFn(item, index, this.collection)) { - yield this.mapFn( - item as TFilterOutput, - index, - this.collection, - ); - } else { - yield item; - } + for await (const [index, item] of this.collection.entries()) { + if (await this.predicateFn(item, index, this.collection)) { + yield this.mapFn(item as TFilterOutput, index, this.collection); + } else { + yield item; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/async-iterable-collection/_shared/async-when-iterable.ts b/src/collection/async-iterable-collection/_shared/async-when-iterable.ts index 0c872b2e..b6a29035 100644 --- a/src/collection/async-iterable-collection/_shared/async-when-iterable.ts +++ b/src/collection/async-iterable-collection/_shared/async-when-iterable.ts @@ -1,8 +1,6 @@ import { type AsyncModifier, - CollectionError, type IAsyncCollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -13,7 +11,7 @@ export class AsyncWhenIterable { constructor( private collection: IAsyncCollection, - private condition: () => boolean | Promise, + private condition: () => boolean | PromiseLike, private callback: AsyncModifier< IAsyncCollection, IAsyncCollection @@ -21,20 +19,10 @@ export class AsyncWhenIterable ) {} async *[Symbol.asyncIterator](): AsyncIterator { - try { - if (await this.condition()) { - yield* await this.callback(this.collection); - return; - } - yield* this.collection as IAsyncCollection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + if (await this.condition()) { + yield* await this.callback(this.collection); + return; } + yield* this.collection as IAsyncCollection; } } diff --git a/src/collection/async-iterable-collection/async-iterable-collection.ts b/src/collection/async-iterable-collection/async-iterable-collection.ts index 502a110f..9c239a2c 100644 --- a/src/collection/async-iterable-collection/async-iterable-collection.ts +++ b/src/collection/async-iterable-collection/async-iterable-collection.ts @@ -10,7 +10,6 @@ import { type AsyncModifier, type AsyncTap, type AsyncTransform, - CollectionError, type Comparator, type IAsyncCollection, ItemNotFoundCollectionError, @@ -23,6 +22,7 @@ import { type CrossJoinResult, } from "@/contracts/collection/_module"; import { + AsyncErrorHandlerIterable, AsyncCrossJoinIterable, AsyncSlidingIteralbe, AsyncShuffleIterable, @@ -55,9 +55,6 @@ import { AsyncReverseIterable, AsyncSliceIterable, AsyncRepeatIterable, - AsyncAbortIterable, - AsyncDelayIterable, - AsyncTimeoutIterable, } from "@/collection/async-iterable-collection/_shared/_module"; import { type AsyncIterableValue, @@ -66,6 +63,13 @@ import { } from "@/_shared/types"; import { type RecordItem } from "@/_shared/types"; import { simplifyAsyncLazyable } from "@/_shared/utilities"; +import type { TimeSpan } from "@/_module"; +import { abortableIterable, delayIterable, LazyPromise } from "@/_module"; +import { + AbortAsyncError, + TimeoutAsyncError, + timeoutIterable, +} from "@/async/_module"; /** * All methods that return {@link IAsyncCollection} are executed lazly which means they will be executed when the AsyncIterableCollection is iterated with forEach method or "for await of" loop. @@ -132,62 +136,66 @@ export class AsyncIterableCollection reduce( reduceFn: AsyncReduce, TInput>, - ): Promise; + ): LazyPromise; reduce( reduceFn: AsyncReduce, TInput>, // eslint-disable-next-line @typescript-eslint/unified-signatures initialValue: TInput, - ): Promise; + ): LazyPromise; reduce( reduceFn: AsyncReduce, TOutput>, initialValue: TOutput, - ): Promise; - async reduce( + ): LazyPromise; + reduce( reduceFn: AsyncReduce, TOutput>, initialValue?: TOutput, - ): Promise { - if (initialValue === undefined && (await this.isEmpty())) { - throw new TypeCollectionError( - "Reduce of empty array must be inputed a initial value", - ); - } - if (initialValue !== undefined) { - let output = initialValue as TOutput; + ): LazyPromise { + return new LazyPromise(async () => { + if (initialValue === undefined && (await this.isEmpty())) { + throw new TypeCollectionError( + "Reduce of empty array must be inputed a initial value", + ); + } + if (initialValue !== undefined) { + let output = initialValue as TOutput; - for await (const [index, item] of this.entries()) { - output = await reduceFn(output, item, index, this); + for await (const [index, item] of this.entries()) { + output = await reduceFn(output, item, index, this); + } + return output; } - return output; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment - let output: TOutput = (await this.firstOrFail()) as any, - index = 0, - isFirstIteration = true; - for await (const item of this) { - if (!isFirstIteration) { - output = await reduceFn(output, item, index, this); + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment + let output: TOutput = (await this.firstOrFail()) as any, + index = 0, + isFirstIteration = true; + for await (const item of this) { + if (!isFirstIteration) { + output = await reduceFn(output, item, index, this); + } + isFirstIteration = false; + index++; } - isFirstIteration = false; - index++; - } - return output; + return output; + }); } - async join(separator = ","): Promise> { - let str: string | null = null; - for await (const item of this) { - if (typeof item !== "string") { - throw new TypeCollectionError( - "Item type is invalid must be string", - ); - } - if (str === null) { - str = item; - } else { - str = str + separator + item; + join(separator = ","): LazyPromise> { + return new LazyPromise(async () => { + let str: string | null = null; + for await (const item of this) { + if (typeof item !== "string") { + throw new TypeCollectionError( + "Item type is invalid must be string", + ); + } + if (str === null) { + str = item; + } else { + str = str + separator + item; + } } - } - return str as EnsureType; + return str as EnsureType; + }); } collapse(): IAsyncCollection> { @@ -222,8 +230,8 @@ export class AsyncIterableCollection return this.skip((page - 1) * pageSize).take(pageSize); } - async sum(): Promise> { - try { + sum(): LazyPromise> { + return new LazyPromise(async () => { if (await this.isEmpty()) { throw new EmptyCollectionError( "Collection is empty therby operation cannot be performed", @@ -239,19 +247,11 @@ export class AsyncIterableCollection sum += item; } return sum as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async average(): Promise> { - try { + average(): LazyPromise> { + return new LazyPromise(async () => { if (await this.isEmpty()) { throw new EmptyCollectionError( "Collection is empty therby operation cannot be performed", @@ -269,63 +269,57 @@ export class AsyncIterableCollection sum += item; } return (sum / size) as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async median(): Promise> { - if (await this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", - ); - } - const size = await this.size(); - if (size === 0) { - return 0 as EnsureType; - } - const isEven = size % 2 === 0, - items = await this.map((item) => { - if (typeof item !== "number") { - throw new TypeCollectionError( - "Item type is invalid must be number", - ); - } - return item; - }) - .filter((_item, index) => { - if (isEven) { - return index === size / 2 || index === size / 2 - 1; + median(): LazyPromise> { + return new LazyPromise(async () => { + if (await this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", + ); + } + const size = await this.size(); + if (size === 0) { + return 0 as EnsureType; + } + const isEven = size % 2 === 0, + items = await this.map((item) => { + if (typeof item !== "number") { + throw new TypeCollectionError( + "Item type is invalid must be number", + ); } - return index === Math.floor(size / 2); + return item; }) - - .toArray(); - if (isEven) { - const [a, b] = items; - if (a === undefined) { - throw new UnexpectedCollectionError("Is in invalid state"); + .filter((_item, index) => { + if (isEven) { + return index === size / 2 || index === size / 2 - 1; + } + return index === Math.floor(size / 2); + }) + + .toArray(); + if (isEven) { + const [a, b] = items; + if (a === undefined) { + throw new UnexpectedCollectionError("Is in invalid state"); + } + if (b === undefined) { + throw new UnexpectedCollectionError("Is in invalid state"); + } + return ((a + b) / 2) as EnsureType; } - if (b === undefined) { + const [median] = items; + if (median === undefined) { throw new UnexpectedCollectionError("Is in invalid state"); } - return ((a + b) / 2) as EnsureType; - } - const [median] = items; - if (median === undefined) { - throw new UnexpectedCollectionError("Is in invalid state"); - } - return median as EnsureType; + return median as EnsureType; + }); } - async min(): Promise> { - try { + min(): LazyPromise> { + return new LazyPromise(async () => { if (await this.isEmpty()) { throw new EmptyCollectionError( "Collection is empty therby operation cannot be performed", @@ -345,19 +339,11 @@ export class AsyncIterableCollection } } return min as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async max(): Promise> { - try { + max(): LazyPromise> { + return new LazyPromise(async () => { if (await this.isEmpty()) { throw new EmptyCollectionError( "Collection is empty therby operation cannot be performed", @@ -377,21 +363,13 @@ export class AsyncIterableCollection } } return max as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async percentage( + percentage( predicateFn: AsyncPredicate>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { if (await this.isEmpty()) { throw new EmptyCollectionError( "Collection is empty therby operation cannot be performed", @@ -406,42 +384,26 @@ export class AsyncIterableCollection total++; } return (part / total) * 100; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async some( + some( predicateFn: AsyncPredicate, TOutput>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { for await (const [index, item] of this.entries()) { if (await predicateFn(item, index, this)) { return true; } } return false; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async every( + every( predicateFn: AsyncPredicate, TOutput>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { let isTrue = true; for await (const [index, item] of this.entries()) { isTrue &&= await predicateFn(item, index, this); @@ -450,15 +412,7 @@ export class AsyncIterableCollection } } return isTrue; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } take(limit: number): IAsyncCollection { @@ -547,20 +501,12 @@ export class AsyncIterableCollection ); } - async pipe( + pipe( callback: AsyncTransform, TOutput>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { return await callback(this); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } tap( @@ -793,63 +739,57 @@ export class AsyncIterableCollection ); } - async first( + first( predicateFn?: AsyncPredicate, TOutput>, - ): Promise { + ): LazyPromise { return this.firstOr(null, predicateFn); } - async firstOr( + firstOr( defaultValue: AsyncLazyable, predicateFn: AsyncPredicate< TInput, IAsyncCollection, TOutput > = () => true, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { for await (const [index, item] of this.entries()) { if (await predicateFn(item, index, this)) { return item as TOutput; } } return await simplifyAsyncLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async firstOrFail( + firstOrFail( predicateFn?: AsyncPredicate, TOutput>, - ): Promise { - const item = await this.first(predicateFn); - if (item === null) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return item; + ): LazyPromise { + return new LazyPromise(async () => { + const item = await this.first(predicateFn); + if (item === null) { + throw new ItemNotFoundCollectionError("Item was not found"); + } + return item; + }); } - async last( + last( predicateFn?: AsyncPredicate, TOutput>, - ): Promise { + ): LazyPromise { return this.lastOr(null, predicateFn); } - async lastOr( + lastOr( defaultValue: AsyncLazyable, predicateFn: AsyncPredicate< TInput, IAsyncCollection, TOutput > = () => true, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { let matchedItem: TOutput | null = null; for await (const [index, item] of this.entries()) { if (await predicateFn(item, index, this)) { @@ -860,38 +800,32 @@ export class AsyncIterableCollection return matchedItem; } return await simplifyAsyncLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async lastOrFail( + lastOrFail( predicateFn?: AsyncPredicate, TOutput>, - ): Promise { - const item = await this.last(predicateFn); - if (item === null) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return item; + ): LazyPromise { + return new LazyPromise(async () => { + const item = await this.last(predicateFn); + if (item === null) { + throw new ItemNotFoundCollectionError("Item was not found"); + } + return item; + }); } - async before( + before( predicateFn: AsyncPredicate>, - ): Promise { + ): LazyPromise { return this.beforeOr(null, predicateFn); } - async beforeOr( + beforeOr( defaultValue: AsyncLazyable, predicateFn: AsyncPredicate>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { let beforeItem: TInput | null = null, index = 0; for await (const item of this) { @@ -902,38 +836,32 @@ export class AsyncIterableCollection beforeItem = item; } return await simplifyAsyncLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async beforeOrFail( + beforeOrFail( predicateFn: AsyncPredicate>, - ): Promise { - const item = await this.before(predicateFn); - if (item === null) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return item; + ): LazyPromise { + return new LazyPromise(async () => { + const item = await this.before(predicateFn); + if (item === null) { + throw new ItemNotFoundCollectionError("Item was not found"); + } + return item; + }); } - async after( + after( predicateFn: AsyncPredicate>, - ): Promise { + ): LazyPromise { return this.afterOr(null, predicateFn); } - async afterOr( + afterOr( defaultValue: AsyncLazyable, predicateFn: AsyncPredicate>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { let hasMatched = false, index = 0; for await (const item of this) { @@ -944,28 +872,25 @@ export class AsyncIterableCollection index++; } return await simplifyAsyncLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError("!!__messge__!!", error); - } + }); } - async afterOrFail( + afterOrFail( predicateFn: AsyncPredicate>, - ): Promise { - const item = await this.after(predicateFn); - if (item === null) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return item; + ): LazyPromise { + return new LazyPromise(async () => { + const item = await this.after(predicateFn); + if (item === null) { + throw new ItemNotFoundCollectionError("Item was not found"); + } + return item; + }); } - async sole( + sole( predicateFn: AsyncPredicate, TOutput>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { let matchedItem: TOutput | null = null; for await (const [index, item] of this.entries()) { if (await predicateFn(item, index, this)) { @@ -981,43 +906,39 @@ export class AsyncIterableCollection throw new ItemNotFoundCollectionError("Item was not found"); } return matchedItem; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } nth(step: number): IAsyncCollection { return this.filter((_item, index) => index % step === 0); } - delay(timeInMs: number): IAsyncCollection { - return new AsyncIterableCollection( - new AsyncDelayIterable(this, timeInMs), - ); + delay(time: TimeSpan): IAsyncCollection { + return new AsyncIterableCollection(delayIterable(this, time)); } - abort(signal: AbortSignal): IAsyncCollection { + takeUntilAbort(abortSignal: AbortSignal): IAsyncCollection { return new AsyncIterableCollection( - new AsyncAbortIterable(this, signal), + new AsyncErrorHandlerIterable( + abortableIterable(this, abortSignal), + (error) => error instanceof AbortAsyncError, + ), ); } - timeout(timeInMs: number): IAsyncCollection { + takeUntilTimeout(timeInMs: TimeSpan): IAsyncCollection { return new AsyncIterableCollection( - new AsyncTimeoutIterable(this, timeInMs), + new AsyncErrorHandlerIterable( + timeoutIterable(this, timeInMs), + (error) => error instanceof TimeoutAsyncError, + ), ); } - async count( + count( predicateFn: AsyncPredicate>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { let size = 0; for await (const item of this) { if (await predicateFn(item, size, this)) { @@ -1025,67 +946,45 @@ export class AsyncIterableCollection } } return size; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async size(): Promise { + size(): LazyPromise { return this.count(() => true); } - async isEmpty(): Promise { - try { + isEmpty(): LazyPromise { + return new LazyPromise(async () => { for await (const _ of this) { return false; } return true; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async isNotEmpty(): Promise { - return !(await this.isEmpty()); + isNotEmpty(): LazyPromise { + return new LazyPromise(async () => { + return !(await this.isEmpty()); + }); } - async searchFirst( + searchFirst( predicateFn: AsyncPredicate>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { for await (const [index, item] of this.entries()) { if (await predicateFn(item, index, this)) { return index; } } return -1; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async searchLast( + searchLast( predicateFn: AsyncPredicate>, - ): Promise { - try { + ): LazyPromise { + return new LazyPromise(async () => { let matchedIndex = -1; for await (const [index, item] of this.entries()) { if (await predicateFn(item, index, this)) { @@ -1093,40 +992,26 @@ export class AsyncIterableCollection } } return matchedIndex; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } - async forEach( + forEach( callback: AsyncForEach>, - ): Promise { - for await (const [index, item] of this.entries()) { - await callback(item, index, this); - } + ): LazyPromise { + return new LazyPromise(async () => { + for await (const [index, item] of this.entries()) { + await callback(item, index, this); + } + }); } - async toArray(): Promise { - try { + toArray(): LazyPromise { + return new LazyPromise(async () => { const items: TInput[] = []; for await (const item of this) { items.push(item); } return items; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + }); } } diff --git a/src/collection/iterable-collection/_shared/chunk-iterable.ts b/src/collection/iterable-collection/_shared/chunk-iterable.ts index 759eab2a..dc2e87fb 100644 --- a/src/collection/iterable-collection/_shared/chunk-iterable.ts +++ b/src/collection/iterable-collection/_shared/chunk-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type ICollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -17,33 +13,23 @@ export class ChunkIterable implements Iterable> { ) {} *[Symbol.iterator](): Iterator> { - try { - const array: TInput[] = []; - let currentChunkSize = 0; - let isFirstIteration = true; - for (const item of this.collection) { - currentChunkSize %= this.chunkSize; - const isFilled = currentChunkSize === 0; - if (!isFirstIteration && isFilled) { - yield this.makeCollection(array); - array.length = 0; - } - array.push(item); - currentChunkSize++; - isFirstIteration = false; - } - const hasRest = currentChunkSize !== 0; - if (hasRest) { + const array: TInput[] = []; + let currentChunkSize = 0; + let isFirstIteration = true; + for (const item of this.collection) { + currentChunkSize %= this.chunkSize; + const isFilled = currentChunkSize === 0; + if (!isFirstIteration && isFilled) { yield this.makeCollection(array); + array.length = 0; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + array.push(item); + currentChunkSize++; + isFirstIteration = false; + } + const hasRest = currentChunkSize !== 0; + if (hasRest) { + yield this.makeCollection(array); } } } diff --git a/src/collection/iterable-collection/_shared/chunk-while-iterable.ts b/src/collection/iterable-collection/_shared/chunk-while-iterable.ts index 00368107..bce62f28 100644 --- a/src/collection/iterable-collection/_shared/chunk-while-iterable.ts +++ b/src/collection/iterable-collection/_shared/chunk-while-iterable.ts @@ -1,8 +1,6 @@ import { - CollectionError, type Predicate, type ICollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -20,30 +18,20 @@ export class ChunkWhileIterable ) {} *[Symbol.iterator](): Iterator> { - try { - const array: TInput[] = []; - for (const [index, item] of this.collection.entries()) { - if (index === 0) { - array.push(item); - } else if ( - this.predicateFn(item, index, this.makeCollection(array)) - ) { - array.push(item); - } else { - yield this.makeCollection(array); - array.length = 0; - array.push(item); - } + const array: TInput[] = []; + for (const [index, item] of this.collection.entries()) { + if (index === 0) { + array.push(item); + } else if ( + this.predicateFn(item, index, this.makeCollection(array)) + ) { + array.push(item); + } else { + yield this.makeCollection(array); + array.length = 0; + array.push(item); } - yield this.makeCollection(array); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + yield this.makeCollection(array); } } diff --git a/src/collection/iterable-collection/_shared/collapse-iterable.ts b/src/collection/iterable-collection/_shared/collapse-iterable.ts index 409f872e..9b1e4420 100644 --- a/src/collection/iterable-collection/_shared/collapse-iterable.ts +++ b/src/collection/iterable-collection/_shared/collapse-iterable.ts @@ -1,9 +1,7 @@ import { isIterable } from "@/collection/_shared"; import { type Collapse, - CollectionError, type ICollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -13,23 +11,13 @@ export class CollapseIterable implements Iterable> { constructor(private collection: ICollection) {} *[Symbol.iterator](): Iterator> { - try { - for (const item of this.collection) { - if (isIterable(item)) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - yield* item as any; - } else { - yield item as Collapse; - } + for (const item of this.collection) { + if (isIterable(item)) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + yield* item as any; + } else { + yield item as Collapse; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/iterable-collection/_shared/count-by-iterable.ts b/src/collection/iterable-collection/_shared/count-by-iterable.ts index bd2a642a..3ee805bf 100644 --- a/src/collection/iterable-collection/_shared/count-by-iterable.ts +++ b/src/collection/iterable-collection/_shared/count-by-iterable.ts @@ -1,9 +1,4 @@ -import { - CollectionError, - type ICollection, - type Map, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection, type Map } from "@/contracts/collection/_module"; import { type RecordItem } from "@/_shared/types"; /** @@ -20,27 +15,17 @@ export class CountByIterable ) {} *[Symbol.iterator](): Iterator> { - try { - const map = new Map(); - for (const [index, item] of this.collection.entries()) { - const key = this.selectFn(item, index, this.collection); - if (!map.has(key)) { - map.set(key, 0); - } - const counter = map.get(key); - if (counter !== undefined) { - map.set(key, counter + 1); - } + const map = new Map(); + for (const [index, item] of this.collection.entries()) { + const key = this.selectFn(item, index, this.collection); + if (!map.has(key)) { + map.set(key, 0); } - yield* map; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const counter = map.get(key); + if (counter !== undefined) { + map.set(key, counter + 1); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + yield* map; } } diff --git a/src/collection/iterable-collection/_shared/cross-join-iterable.ts b/src/collection/iterable-collection/_shared/cross-join-iterable.ts index 0cade788..62533e0e 100644 --- a/src/collection/iterable-collection/_shared/cross-join-iterable.ts +++ b/src/collection/iterable-collection/_shared/cross-join-iterable.ts @@ -3,10 +3,7 @@ import type { CrossJoinResult, ICollection, } from "@/contracts/collection/_module"; -import { - CollectionError, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import {} from "@/contracts/collection/_module"; export class CrossJoinIterable implements Iterable> @@ -20,49 +17,33 @@ export class CrossJoinIterable ) {} *[Symbol.iterator](): Iterator> { - try { - const combinations = this.makeCollection([ - this.collection, - this.makeCollection(this.iterable), - ] as ICollection[]) - .reduce>>( - (a, b) => { - return a - .map((x) => { - return b.map((y) => { - return [...x, y]; - }); - }) - .reduce>>( - (c, b) => c.append(b), - this.makeCollection>( - [], - ), - ); - }, - this.makeCollection([[] as Array]), - ) - .map((combination) => { - // Flatting the array - return combination.reduce>( - (a, b) => { - return [ - ...a, - ...(isIterable(b) ? b : [b]), - ] as Array; - }, - [], - ); - }); - yield* combinations as Iterable>; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + const combinations = this.makeCollection([ + this.collection, + this.makeCollection(this.iterable), + ] as ICollection[]) + .reduce>>( + (a, b) => { + return a + .map((x) => { + return b.map((y) => { + return [...x, y]; + }); + }) + .reduce>>( + (c, b) => c.append(b), + this.makeCollection>([]), + ); + }, + this.makeCollection([[] as Array]), + ) + .map((combination) => { + // Flatting the array + return combination.reduce>((a, b) => { + return [...a, ...(isIterable(b) ? b : [b])] as Array< + TInput | TExtended + >; + }, []); + }); + yield* combinations as Iterable>; } } diff --git a/src/collection/iterable-collection/_shared/entries-iterable.ts b/src/collection/iterable-collection/_shared/entries-iterable.ts index 2424925d..3144ebeb 100644 --- a/src/collection/iterable-collection/_shared/entries-iterable.ts +++ b/src/collection/iterable-collection/_shared/entries-iterable.ts @@ -1,7 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, -} from "@/contracts/collection/_shared"; +import {} from "@/contracts/collection/_shared"; import { type RecordItem } from "@/_shared/types"; /** @@ -13,20 +10,10 @@ export class EntriesIterable constructor(private iterable: Iterable) {} *[Symbol.iterator](): Iterator> { - try { - let index = 0; - for (const item of this.iterable) { - yield [index, item]; - index++; - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + let index = 0; + for (const item of this.iterable) { + yield [index, item]; + index++; } } } diff --git a/src/collection/iterable-collection/_shared/filter-iterable.ts b/src/collection/iterable-collection/_shared/filter-iterable.ts index b5c08ec1..b8ee2eb4 100644 --- a/src/collection/iterable-collection/_shared/filter-iterable.ts +++ b/src/collection/iterable-collection/_shared/filter-iterable.ts @@ -1,8 +1,6 @@ import { - CollectionError, type Predicate, type ICollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -17,20 +15,10 @@ export class FilterIterable ) {} *[Symbol.iterator](): Iterator { - try { - for (const [index, item] of this.collection.entries()) { - if (this.predicateFn(item, index, this.collection)) { - yield item as TOutput; - } + for (const [index, item] of this.collection.entries()) { + if (this.predicateFn(item, index, this.collection)) { + yield item as TOutput; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/iterable-collection/_shared/flat-map-iterable.ts b/src/collection/iterable-collection/_shared/flat-map-iterable.ts index 92bdb923..4c65d5cc 100644 --- a/src/collection/iterable-collection/_shared/flat-map-iterable.ts +++ b/src/collection/iterable-collection/_shared/flat-map-iterable.ts @@ -1,9 +1,4 @@ -import { - CollectionError, - type ICollection, - type Map, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection, type Map } from "@/contracts/collection/_module"; /** * @internal @@ -15,18 +10,8 @@ export class FlatMapIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - for (const [index, item] of this.collection.entries()) { - yield* this.mapFn(item, index, this.collection); - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + for (const [index, item] of this.collection.entries()) { + yield* this.mapFn(item, index, this.collection); } } } diff --git a/src/collection/iterable-collection/_shared/group-by-iterable.ts b/src/collection/iterable-collection/_shared/group-by-iterable.ts index 00167ab1..12c1aa1a 100644 --- a/src/collection/iterable-collection/_shared/group-by-iterable.ts +++ b/src/collection/iterable-collection/_shared/group-by-iterable.ts @@ -1,9 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, - type ICollection, - type Map, -} from "@/contracts/collection/_module"; +import { type ICollection, type Map } from "@/contracts/collection/_module"; import { type RecordItem } from "@/_shared/types"; /** @@ -24,29 +19,19 @@ export class GroupByIterable ) {} *[Symbol.iterator](): Iterator>> { - try { - const map = new Map>(); - for (const [index, item] of this.collection.entries()) { - const key = this.selectFn(item, index, this.collection); - let array = map.get(key); - if (array === undefined) { - array = []; - map.set(key, array); - } - array.push(item); + const map = new Map>(); + for (const [index, item] of this.collection.entries()) { + const key = this.selectFn(item, index, this.collection); + let array = map.get(key); + if (array === undefined) { + array = []; map.set(key, array); } - yield* this.makeCollection(map).map< - RecordItem> - >(([key, value]) => [key, this.makeCollection(value)]); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + array.push(item); + map.set(key, array); } + yield* this.makeCollection(map).map< + RecordItem> + >(([key, value]) => [key, this.makeCollection(value)]); } } diff --git a/src/collection/iterable-collection/_shared/insert-after-iterable.ts b/src/collection/iterable-collection/_shared/insert-after-iterable.ts index da98b754..8c985159 100644 --- a/src/collection/iterable-collection/_shared/insert-after-iterable.ts +++ b/src/collection/iterable-collection/_shared/insert-after-iterable.ts @@ -1,8 +1,6 @@ import { - CollectionError, type Predicate, type ICollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -18,26 +16,13 @@ export class InsertAfterIterable ) {} *[Symbol.iterator](): Iterator { - try { - let hasMatched = false; - for (const [index, item] of this.collection.entries()) { - yield item; - if ( - !hasMatched && - this.predicateFn(item, index, this.collection) - ) { - yield* this.iterable; - hasMatched = true; - } + let hasMatched = false; + for (const [index, item] of this.collection.entries()) { + yield item; + if (!hasMatched && this.predicateFn(item, index, this.collection)) { + yield* this.iterable; + hasMatched = true; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/iterable-collection/_shared/insert-before-iterable.ts b/src/collection/iterable-collection/_shared/insert-before-iterable.ts index c2549c04..b0461d5f 100644 --- a/src/collection/iterable-collection/_shared/insert-before-iterable.ts +++ b/src/collection/iterable-collection/_shared/insert-before-iterable.ts @@ -1,8 +1,6 @@ import { - CollectionError, type Predicate, type ICollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -18,26 +16,13 @@ export class InsertBeforeIterable ) {} *[Symbol.iterator](): Iterator { - try { - let hasMatched = false; - for (const [index, item] of this.collection.entries()) { - if ( - !hasMatched && - this.predicateFn(item, index, this.collection) - ) { - yield* this.iterable; - hasMatched = true; - } - yield item; + let hasMatched = false; + for (const [index, item] of this.collection.entries()) { + if (!hasMatched && this.predicateFn(item, index, this.collection)) { + yield* this.iterable; + hasMatched = true; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + yield item; } } } diff --git a/src/collection/iterable-collection/_shared/map-iterable.ts b/src/collection/iterable-collection/_shared/map-iterable.ts index 9ddbd267..81176c08 100644 --- a/src/collection/iterable-collection/_shared/map-iterable.ts +++ b/src/collection/iterable-collection/_shared/map-iterable.ts @@ -1,9 +1,4 @@ -import { - CollectionError, - type ICollection, - type Map, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection, type Map } from "@/contracts/collection/_module"; /** * @internal @@ -15,18 +10,8 @@ export class MapIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - for (const [index, item] of this.collection.entries()) { - yield this.mapFn(item, index, this.collection); - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + for (const [index, item] of this.collection.entries()) { + yield this.mapFn(item, index, this.collection); } } } diff --git a/src/collection/iterable-collection/_shared/merge-iterable.ts b/src/collection/iterable-collection/_shared/merge-iterable.ts index 95d8b623..2ed916a0 100644 --- a/src/collection/iterable-collection/_shared/merge-iterable.ts +++ b/src/collection/iterable-collection/_shared/merge-iterable.ts @@ -1,7 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import {} from "@/contracts/collection/_module"; /** * @internal @@ -15,17 +12,7 @@ export class MergeIterable ) {} *[Symbol.iterator](): Iterator { - try { - yield* this.iterableA; - yield* this.iterableB; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + yield* this.iterableA; + yield* this.iterableB; } } diff --git a/src/collection/iterable-collection/_shared/pad-end-iterable.ts b/src/collection/iterable-collection/_shared/pad-end-iterable.ts index 761d7e94..8f0659d4 100644 --- a/src/collection/iterable-collection/_shared/pad-end-iterable.ts +++ b/src/collection/iterable-collection/_shared/pad-end-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, - type ICollection, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -20,30 +16,20 @@ export class PadEndIterable ) {} *[Symbol.iterator](): Iterator { - try { - const fillCollections = this.makeCollection(this.fillItems); - const fillSize = fillCollections.size(); - const size = this.collection.size(); - const repeat = Math.floor((this.maxLength - size) / fillSize); - let resultCollection: ICollection = - this.makeCollection([]); - for (let index = 0; index < repeat; index++) { - resultCollection = resultCollection.append(fillCollections); - } - const restAmount = this.maxLength - (repeat * fillSize + size); - resultCollection = resultCollection.append( - fillCollections.slice(0, restAmount), - ); - resultCollection = resultCollection.prepend(this.collection); - yield* resultCollection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + const fillCollections = this.makeCollection(this.fillItems); + const fillSize = fillCollections.size(); + const size = this.collection.size(); + const repeat = Math.floor((this.maxLength - size) / fillSize); + let resultCollection: ICollection = + this.makeCollection([]); + for (let index = 0; index < repeat; index++) { + resultCollection = resultCollection.append(fillCollections); } + const restAmount = this.maxLength - (repeat * fillSize + size); + resultCollection = resultCollection.append( + fillCollections.slice(0, restAmount), + ); + resultCollection = resultCollection.prepend(this.collection); + yield* resultCollection; } } diff --git a/src/collection/iterable-collection/_shared/pad-start-iterable.ts b/src/collection/iterable-collection/_shared/pad-start-iterable.ts index ef2e95da..e1ceb289 100644 --- a/src/collection/iterable-collection/_shared/pad-start-iterable.ts +++ b/src/collection/iterable-collection/_shared/pad-start-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, - type ICollection, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -20,30 +16,20 @@ export class PadStartIterable ) {} *[Symbol.iterator](): Iterator { - try { - const fillCollections = this.makeCollection(this.fillItems); - const fillSize = fillCollections.size(); - const size = this.collection.size(); - const repeat = Math.floor((this.maxLength - size) / fillSize); - let resultCollection: ICollection = - this.makeCollection([]); - for (let index = 0; index < repeat; index++) { - resultCollection = resultCollection.append(fillCollections); - } - const restAmount = this.maxLength - (repeat * fillSize + size); - resultCollection = resultCollection.append( - fillCollections.slice(0, restAmount), - ); - resultCollection = resultCollection.append(this.collection); - yield* resultCollection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + const fillCollections = this.makeCollection(this.fillItems); + const fillSize = fillCollections.size(); + const size = this.collection.size(); + const repeat = Math.floor((this.maxLength - size) / fillSize); + let resultCollection: ICollection = + this.makeCollection([]); + for (let index = 0; index < repeat; index++) { + resultCollection = resultCollection.append(fillCollections); } + const restAmount = this.maxLength - (repeat * fillSize + size); + resultCollection = resultCollection.append( + fillCollections.slice(0, restAmount), + ); + resultCollection = resultCollection.append(this.collection); + yield* resultCollection; } } diff --git a/src/collection/iterable-collection/_shared/partion-iterable.ts b/src/collection/iterable-collection/_shared/partion-iterable.ts index 34a4a07e..caf6c4e7 100644 --- a/src/collection/iterable-collection/_shared/partion-iterable.ts +++ b/src/collection/iterable-collection/_shared/partion-iterable.ts @@ -1,8 +1,6 @@ import { - CollectionError, type Predicate, type ICollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -19,26 +17,16 @@ export class PartionIterable implements Iterable> { ) {} *[Symbol.iterator](): Iterator> { - try { - const arrayA: TInput[] = []; - const arrayB: TInput[] = []; - for (const [index, item] of this.collection.entries()) { - if (this.predicateFn(item, index, this.collection)) { - arrayA.push(item); - } else { - arrayB.push(item); - } + const arrayA: TInput[] = []; + const arrayB: TInput[] = []; + for (const [index, item] of this.collection.entries()) { + if (this.predicateFn(item, index, this.collection)) { + arrayA.push(item); + } else { + arrayB.push(item); } - yield this.makeCollection(arrayA); - yield this.makeCollection(arrayB); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + yield this.makeCollection(arrayA); + yield this.makeCollection(arrayB); } } diff --git a/src/collection/iterable-collection/_shared/repeat-iterable.ts b/src/collection/iterable-collection/_shared/repeat-iterable.ts index 97e77a51..cfe954d8 100644 --- a/src/collection/iterable-collection/_shared/repeat-iterable.ts +++ b/src/collection/iterable-collection/_shared/repeat-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, - type ICollection, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -17,20 +13,10 @@ export class RepeatIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - let collection = this.makeCollection([]); - for (let index = 0; index < this.amount; index++) { - collection = collection.append(this.collection); - } - yield* collection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + let collection = this.makeCollection([]); + for (let index = 0; index < this.amount; index++) { + collection = collection.append(this.collection); } + yield* collection; } } diff --git a/src/collection/iterable-collection/_shared/reverse-iterable.ts b/src/collection/iterable-collection/_shared/reverse-iterable.ts index a1fa5d2d..50ea777c 100644 --- a/src/collection/iterable-collection/_shared/reverse-iterable.ts +++ b/src/collection/iterable-collection/_shared/reverse-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, - type ICollection, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -18,22 +14,12 @@ export class ReverseIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - yield* this.collection - .chunk(this.chunkSize) - .map((item) => this.makeCollection([...item].reverse())) - .reduce( - (collection, item) => collection.prepend(item), - this.makeCollection([]), - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, + yield* this.collection + .chunk(this.chunkSize) + .map((item) => this.makeCollection([...item].reverse())) + .reduce( + (collection, item) => collection.prepend(item), + this.makeCollection([]), ); - } } } diff --git a/src/collection/iterable-collection/_shared/shuffle-iterable.ts b/src/collection/iterable-collection/_shared/shuffle-iterable.ts index 3acf1eab..763d3898 100644 --- a/src/collection/iterable-collection/_shared/shuffle-iterable.ts +++ b/src/collection/iterable-collection/_shared/shuffle-iterable.ts @@ -1,7 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, -} from "@/contracts/collection/_shared"; +import {} from "@/contracts/collection/_shared"; /** * @internal @@ -13,27 +10,17 @@ export class ShuffleIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - const newArray = [...this.iterable]; - for (let i = newArray.length - 1; i > 0; i--) { - const j = Math.floor(this.mathRandom() * (i + 1)); - const temp = newArray[i]; - if (newArray[j] !== undefined) { - newArray[i] = newArray[j]; - } - if (temp !== undefined) { - newArray[j] = temp; - } + const newArray = [...this.iterable]; + for (let i = newArray.length - 1; i > 0; i--) { + const j = Math.floor(this.mathRandom() * (i + 1)); + const temp = newArray[i]; + if (newArray[j] !== undefined) { + newArray[i] = newArray[j]; } - yield* newArray; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (temp !== undefined) { + newArray[j] = temp; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + yield* newArray; } } diff --git a/src/collection/iterable-collection/_shared/skip-iterable.ts b/src/collection/iterable-collection/_shared/skip-iterable.ts index 3a5b62a0..9c0ee280 100644 --- a/src/collection/iterable-collection/_shared/skip-iterable.ts +++ b/src/collection/iterable-collection/_shared/skip-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type ICollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -14,21 +10,9 @@ export class SkipIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - if (this.offset < 0) { - this.offset = this.collection.size() + this.offset; - } - yield* this.collection.skipWhile( - (_item, index) => index < this.offset, - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + if (this.offset < 0) { + this.offset = this.collection.size() + this.offset; } + yield* this.collection.skipWhile((_item, index) => index < this.offset); } } diff --git a/src/collection/iterable-collection/_shared/skip-until-iterable.ts b/src/collection/iterable-collection/_shared/skip-until-iterable.ts index 092c91bd..6acd60be 100644 --- a/src/collection/iterable-collection/_shared/skip-until-iterable.ts +++ b/src/collection/iterable-collection/_shared/skip-until-iterable.ts @@ -1,8 +1,6 @@ import { - CollectionError, type Predicate, type ICollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -15,24 +13,14 @@ export class SkipUntilIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - let hasMatched = false; - for (const [index, item] of this.collection.entries()) { - if (!hasMatched) { - hasMatched = this.predicateFn(item, index, this.collection); - } - if (hasMatched) { - yield item; - } + let hasMatched = false; + for (const [index, item] of this.collection.entries()) { + if (!hasMatched) { + hasMatched = this.predicateFn(item, index, this.collection); } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (hasMatched) { + yield item; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/iterable-collection/_shared/slice-iterable.ts b/src/collection/iterable-collection/_shared/slice-iterable.ts index d5dcbd65..c9f6090d 100644 --- a/src/collection/iterable-collection/_shared/slice-iterable.ts +++ b/src/collection/iterable-collection/_shared/slice-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, - type ICollection, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -15,32 +11,22 @@ export class SliceIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - const size = this.collection.size(); - let { start, end } = this; - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = size; - } - if (start < 0) { - start = size + start; - } - if (end < 0) { - end = size + end; - } - yield* this.collection.filter((_item, index) => { - return start <= index && index < end; - }); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + const size = this.collection.size(); + let { start, end } = this; + if (start === undefined) { + start = 0; } + if (end === undefined) { + end = size; + } + if (start < 0) { + start = size + start; + } + if (end < 0) { + end = size + end; + } + yield* this.collection.filter((_item, index) => { + return start <= index && index < end; + }); } } diff --git a/src/collection/iterable-collection/_shared/sliding-iterable.ts b/src/collection/iterable-collection/_shared/sliding-iterable.ts index 531181ab..bb8f5377 100644 --- a/src/collection/iterable-collection/_shared/sliding-iterable.ts +++ b/src/collection/iterable-collection/_shared/sliding-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type ICollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -15,30 +11,20 @@ export class SlidingIteralbe implements Iterable> { ) {} *[Symbol.iterator](): Iterator> { - try { - if (this.step <= 0) { - return; - } - const size = this.collection.size(); + if (this.step <= 0) { + return; + } + const size = this.collection.size(); - for (let index = 0; index < size; index += this.step) { - const start = index; - const end = index + this.chunkSize; + for (let index = 0; index < size; index += this.step) { + const start = index; + const end = index + this.chunkSize; - yield this.collection.slice(start, end); + yield this.collection.slice(start, end); - if (end >= size) { - break; - } - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (end >= size) { + break; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/iterable-collection/_shared/sort-iterable.ts b/src/collection/iterable-collection/_shared/sort-iterable.ts index 03adf25a..8a0a6d72 100644 --- a/src/collection/iterable-collection/_shared/sort-iterable.ts +++ b/src/collection/iterable-collection/_shared/sort-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, - type Comparator, -} from "@/contracts/collection/_module"; +import { type Comparator } from "@/contracts/collection/_module"; /** * @internal @@ -14,16 +10,6 @@ export class SortIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - yield* [...this.iterable].sort(this.comparator); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + yield* [...this.iterable].sort(this.comparator); } } diff --git a/src/collection/iterable-collection/_shared/split-iterable.ts b/src/collection/iterable-collection/_shared/split-iterable.ts index 8df7646b..c83a3ddd 100644 --- a/src/collection/iterable-collection/_shared/split-iterable.ts +++ b/src/collection/iterable-collection/_shared/split-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type ICollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -18,41 +14,31 @@ export class SplitIterable implements Iterable> { ) {} *[Symbol.iterator](): Iterator> { - try { - const size = this.collection.size(), - minChunkSize = Math.floor(size / this.chunkAmount), - restSize = size % this.chunkAmount, - chunkSizes = Array.from({ - length: this.chunkAmount, - }).fill(minChunkSize); + const size = this.collection.size(), + minChunkSize = Math.floor(size / this.chunkAmount), + restSize = size % this.chunkAmount, + chunkSizes = Array.from({ + length: this.chunkAmount, + }).fill(minChunkSize); - for (let i = 1; i <= restSize; i++) { - const chunkIndex = (i - 1) % this.chunkAmount; - if (chunkSizes[chunkIndex]) { - chunkSizes[chunkIndex] = chunkSizes[chunkIndex] + 1; - } + for (let i = 1; i <= restSize; i++) { + const chunkIndex = (i - 1) % this.chunkAmount; + if (chunkSizes[chunkIndex]) { + chunkSizes[chunkIndex] = chunkSizes[chunkIndex] + 1; } + } - const iterator = this.collection.toIterator(); - const array: TInput[] = []; - for (const chunkSize of chunkSizes) { - for (let i = 0; i < chunkSize; i++) { - const item = iterator.next(); - if (item.value !== undefined) { - array.push(item.value); - } + const iterator = this.collection.toIterator(); + const array: TInput[] = []; + for (const chunkSize of chunkSizes) { + for (let i = 0; i < chunkSize; i++) { + const item = iterator.next(); + if (item.value !== undefined) { + array.push(item.value); } - yield this.makeCollection(array); - array.length = 0; - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + yield this.makeCollection(array); + array.length = 0; } } } diff --git a/src/collection/iterable-collection/_shared/take-iterable.ts b/src/collection/iterable-collection/_shared/take-iterable.ts index 618b9950..96cdf9fa 100644 --- a/src/collection/iterable-collection/_shared/take-iterable.ts +++ b/src/collection/iterable-collection/_shared/take-iterable.ts @@ -1,8 +1,4 @@ -import { - CollectionError, - type ICollection, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection } from "@/contracts/collection/_module"; /** * @internal @@ -14,21 +10,9 @@ export class TakeIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - if (this.limit < 0) { - this.limit = this.collection.size() + this.limit; - } - yield* this.collection.takeWhile( - (_item, index) => index < this.limit, - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + if (this.limit < 0) { + this.limit = this.collection.size() + this.limit; } + yield* this.collection.takeWhile((_item, index) => index < this.limit); } } diff --git a/src/collection/iterable-collection/_shared/take-until-iterable.ts b/src/collection/iterable-collection/_shared/take-until-iterable.ts index 1e41a4c8..3137de10 100644 --- a/src/collection/iterable-collection/_shared/take-until-iterable.ts +++ b/src/collection/iterable-collection/_shared/take-until-iterable.ts @@ -1,8 +1,6 @@ import { - CollectionError, type Predicate, type ICollection, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -15,21 +13,11 @@ export class TakeUntilIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - for (const [index, item] of this.collection.entries()) { - if (this.predicateFn(item, index, this.collection)) { - break; - } - yield item; + for (const [index, item] of this.collection.entries()) { + if (this.predicateFn(item, index, this.collection)) { + break; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + yield item; } } } diff --git a/src/collection/iterable-collection/_shared/tap-iterable.ts b/src/collection/iterable-collection/_shared/tap-iterable.ts index 901e4bcd..63378890 100644 --- a/src/collection/iterable-collection/_shared/tap-iterable.ts +++ b/src/collection/iterable-collection/_shared/tap-iterable.ts @@ -1,9 +1,4 @@ -import { - CollectionError, - type ICollection, - type Tap, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection, type Tap } from "@/contracts/collection/_module"; /** * @internal @@ -15,17 +10,7 @@ export class TapIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - this.callback(this.collection); - yield* this.collection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + this.callback(this.collection); + yield* this.collection; } } diff --git a/src/collection/iterable-collection/_shared/unique-iterable.ts b/src/collection/iterable-collection/_shared/unique-iterable.ts index 0144567e..35896f10 100644 --- a/src/collection/iterable-collection/_shared/unique-iterable.ts +++ b/src/collection/iterable-collection/_shared/unique-iterable.ts @@ -1,9 +1,4 @@ -import { - CollectionError, - type ICollection, - type Map, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import { type ICollection, type Map } from "@/contracts/collection/_module"; /** * @internal @@ -17,24 +12,14 @@ export class UniqueIterable implements Iterable { ) {} *[Symbol.iterator](): Iterator { - try { - const set = new Set([]); + const set = new Set([]); - for (const [index, item] of this.collection.entries()) { - const item_ = this.callback(item, index, this.collection); - if (!set.has(item_)) { - yield item; - } - set.add(item_); + for (const [index, item] of this.collection.entries()) { + const item_ = this.callback(item, index, this.collection); + if (!set.has(item_)) { + yield item; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + set.add(item_); } } } diff --git a/src/collection/iterable-collection/_shared/update-iterable.ts b/src/collection/iterable-collection/_shared/update-iterable.ts index 6d42feff..fb39dc5d 100644 --- a/src/collection/iterable-collection/_shared/update-iterable.ts +++ b/src/collection/iterable-collection/_shared/update-iterable.ts @@ -1,9 +1,7 @@ import { - CollectionError, type Predicate, type ICollection, type Map, - UnexpectedCollectionError, type ChangendItem, } from "@/contracts/collection/_module"; @@ -26,26 +24,12 @@ export class UpdateIterable *[Symbol.iterator](): Iterator< ChangendItem > { - try { - for (const [index, item] of this.collection.entries()) { - if (this.predicateFn(item, index, this.collection)) { - yield this.mapFn( - item as TFilterOutput, - index, - this.collection, - ); - } else { - yield item; - } + for (const [index, item] of this.collection.entries()) { + if (this.predicateFn(item, index, this.collection)) { + yield this.mapFn(item as TFilterOutput, index, this.collection); + } else { + yield item; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } } } diff --git a/src/collection/iterable-collection/_shared/when-iterable.ts b/src/collection/iterable-collection/_shared/when-iterable.ts index 68c8e070..d7ebf4ad 100644 --- a/src/collection/iterable-collection/_shared/when-iterable.ts +++ b/src/collection/iterable-collection/_shared/when-iterable.ts @@ -1,8 +1,6 @@ import { - CollectionError, type ICollection, type Modifier, - UnexpectedCollectionError, } from "@/contracts/collection/_module"; /** @@ -18,20 +16,10 @@ export class WhenIterable ) {} *[Symbol.iterator](): Iterator { - try { - if (this.condition()) { - yield* this.callback(this.collection); - return; - } - yield* this.collection as ICollection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + if (this.condition()) { + yield* this.callback(this.collection); + return; } + yield* this.collection as ICollection; } } diff --git a/src/collection/iterable-collection/_shared/zip-iterable.ts b/src/collection/iterable-collection/_shared/zip-iterable.ts index 44593a19..85599bc8 100644 --- a/src/collection/iterable-collection/_shared/zip-iterable.ts +++ b/src/collection/iterable-collection/_shared/zip-iterable.ts @@ -1,7 +1,4 @@ -import { - CollectionError, - UnexpectedCollectionError, -} from "@/contracts/collection/_module"; +import {} from "@/contracts/collection/_module"; import { type RecordItem } from "@/_shared/types"; /** @@ -16,26 +13,16 @@ export class ZipIterable ) {} *[Symbol.iterator](): Iterator> { - try { - const iteratorA = this.iterableA[Symbol.iterator](), - iteratorB = this.iterableB[Symbol.iterator](); - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - while (true) { - const itemA = iteratorA.next(), - itemB = iteratorB.next(); - if (itemA.done || itemB.done) { - break; - } - yield [itemA.value, itemB.value]; + const iteratorA = this.iterableA[Symbol.iterator](), + iteratorB = this.iterableB[Symbol.iterator](); + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const itemA = iteratorA.next(), + itemB = iteratorB.next(); + if (itemA.done || itemB.done) { + break; } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + yield [itemA.value, itemB.value]; } } } diff --git a/src/collection/iterable-collection/iterable-collection.ts b/src/collection/iterable-collection/iterable-collection.ts index 4978297b..67139dbd 100644 --- a/src/collection/iterable-collection/iterable-collection.ts +++ b/src/collection/iterable-collection/iterable-collection.ts @@ -4,7 +4,6 @@ import { type Collapse, - CollectionError, type Comparator, type Predicate, type ForEach, @@ -80,17 +79,7 @@ export class IterableCollection implements ICollection { constructor(private iterable: Iterable) {} *[Symbol.iterator](): Iterator { - try { - yield* this.iterable; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + yield* this.iterable; } toIterator(): Iterator { @@ -143,70 +132,50 @@ export class IterableCollection implements ICollection { reduceFn: Reduce, TOutput>, initialValue?: TOutput, ): TOutput { - try { - if (initialValue === undefined && this.isEmpty()) { - throw new TypeCollectionError( - "Reduce of empty array must be inputed a initial value", - ); - } - if (initialValue !== undefined) { - let output = initialValue as TOutput, - index = 0; - for (const item of this) { - output = reduceFn(output, item, index, this); - index++; - } - return output; - } - - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unnecessary-type-assertion, @typescript-eslint/no-explicit-any - let output: TOutput = this.firstOrFail() as any, - index = 0, - isFirstIteration = true; + if (initialValue === undefined && this.isEmpty()) { + throw new TypeCollectionError( + "Reduce of empty array must be inputed a initial value", + ); + } + if (initialValue !== undefined) { + let output = initialValue as TOutput, + index = 0; for (const item of this) { - if (!isFirstIteration) { - output = reduceFn(output, item, index, this); - } - isFirstIteration = false; + output = reduceFn(output, item, index, this); index++; } return output; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unnecessary-type-assertion, @typescript-eslint/no-explicit-any + let output: TOutput = this.firstOrFail() as any, + index = 0, + isFirstIteration = true; + for (const item of this) { + if (!isFirstIteration) { + output = reduceFn(output, item, index, this); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + isFirstIteration = false; + index++; } + return output; } join(separator = ","): EnsureType { - try { - let str: string | null = null; - for (const item of this) { - if (typeof item !== "string") { - throw new TypeCollectionError( - "Item type is invalid must be string", - ); - } - if (str === null) { - str = item as string; - } else { - str = str + separator + (item as string); - } + let str: string | null = null; + for (const item of this) { + if (typeof item !== "string") { + throw new TypeCollectionError( + "Item type is invalid must be string", + ); } - return str as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (str === null) { + str = item as string; + } else { + str = str + separator + (item as string); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return str as EnsureType; } collapse(): ICollection> { @@ -236,61 +205,41 @@ export class IterableCollection implements ICollection { } sum(): EnsureType { - try { - if (this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", + if (this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", + ); + } + let sum = 0; + for (const item of this) { + if (typeof item !== "number") { + throw new TypeCollectionError( + "Item type is invalid must be number", ); } - let sum = 0; - for (const item of this) { - if (typeof item !== "number") { - throw new TypeCollectionError( - "Item type is invalid must be number", - ); - } - sum += item; - } - return sum as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + sum += item; } + return sum as EnsureType; } average(): EnsureType { - try { - if (this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", + if (this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", + ); + } + let size = 0, + sum = 0; + for (const item of this) { + if (typeof item !== "number") { + throw new TypeCollectionError( + "Item type is invalid must be number", ); } - let size = 0, - sum = 0; - for (const item of this) { - if (typeof item !== "number") { - throw new TypeCollectionError( - "Item type is invalid must be number", - ); - } - size++; - sum += item; - } - return (sum / size) as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + size++; + sum += item; } + return (sum / size) as EnsureType; } median(): EnsureType { @@ -338,142 +287,92 @@ export class IterableCollection implements ICollection { } min(): EnsureType { - try { - if (this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", + if (this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", + ); + } + let min = 0; + for (const item of this) { + if (typeof item !== "number") { + throw new TypeCollectionError( + "Item type is invalid must be number", ); } - let min = 0; - for (const item of this) { - if (typeof item !== "number") { - throw new TypeCollectionError( - "Item type is invalid must be number", - ); - } - if (min === 0) { - min = item; - } else if (min > item) { - min = item; - } + if (min === 0) { + min = item; + } else if (min > item) { + min = item; } - return min as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return min as EnsureType; } max(): EnsureType { - try { - if (this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", + if (this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", + ); + } + let max = 0; + for (const item of this) { + if (typeof item !== "number") { + throw new TypeCollectionError( + "Item type is invalid must be number", ); } - let max = 0; - for (const item of this) { - if (typeof item !== "number") { - throw new TypeCollectionError( - "Item type is invalid must be number", - ); - } - if (max === 0) { - max = item; - } else if (max < item) { - max = item; - } - } - return max as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (max === 0) { + max = item; + } else if (max < item) { + max = item; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return max as EnsureType; } percentage(predicateFn: Predicate>): number { - try { - if (this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", - ); - } - let part = 0, - total = 0; - for (const item of this) { - if (predicateFn(item, total, this)) { - part++; - } - total++; - } - return (part / total) * 100; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, + if (this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", ); } + let part = 0, + total = 0; + for (const item of this) { + if (predicateFn(item, total, this)) { + part++; + } + total++; + } + return (part / total) * 100; } some( predicateFn: Predicate, TOutput>, ): boolean { - try { - let index = 0; - for (const item of this) { - if (predicateFn(item, index, this)) { - return true; - } - index++; + let index = 0; + for (const item of this) { + if (predicateFn(item, index, this)) { + return true; } - return false; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; } + return false; } every( predicateFn: Predicate, TOutput>, ): boolean { - try { - let index = 0, - isTrue = true; - for (const item of this) { - isTrue &&= predicateFn(item, index, this); - if (!isTrue) { - break; - } - index++; + let index = 0, + isTrue = true; + for (const item of this) { + isTrue &&= predicateFn(item, index, this); + if (!isTrue) { + break; } - return isTrue; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; } + return isTrue; } take(limit: number): ICollection { @@ -543,17 +442,7 @@ export class IterableCollection implements ICollection { pipe( callback: Transform, TOutput>, ): TOutput { - try { - return callback(this); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return callback(this); } tap(callback: Tap>): ICollection { @@ -765,17 +654,7 @@ export class IterableCollection implements ICollection { first( predicateFn?: Predicate, TOutput>, ): TOutput | null { - try { - return this.firstOr(null, predicateFn); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.firstOr(null, predicateFn); } firstOr( @@ -783,24 +662,14 @@ export class IterableCollection implements ICollection { predicateFn: Predicate, TOutput> = () => true, ): TOutput | TExtended { - try { - let index = 0; - for (const item of this) { - if (predicateFn(item, index, this)) { - return item as TOutput; - } - index++; + let index = 0; + for (const item of this) { + if (predicateFn(item, index, this)) { + return item as TOutput; } - return simplifyLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; } + return simplifyLazyable(defaultValue); } firstOrFail( @@ -816,17 +685,7 @@ export class IterableCollection implements ICollection { last( predicateFn?: Predicate, TOutput>, ): TOutput | null { - try { - return this.lastOr(null, predicateFn); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.lastOr(null, predicateFn); } lastOr( @@ -834,28 +693,18 @@ export class IterableCollection implements ICollection { predicateFn: Predicate, TOutput> = () => true, ): TOutput | TExtended { - try { - let index = 0; - let matchedItem: TOutput | null = null; - for (const item of this) { - if (predicateFn(item, index, this)) { - matchedItem = item as TOutput; - } - index++; + let index = 0; + let matchedItem: TOutput | null = null; + for (const item of this) { + if (predicateFn(item, index, this)) { + matchedItem = item as TOutput; } - if (matchedItem) { - return matchedItem; - } - return simplifyLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; } + if (matchedItem) { + return matchedItem; + } + return simplifyLazyable(defaultValue); } lastOrFail( @@ -876,26 +725,16 @@ export class IterableCollection implements ICollection { defaultValue: Lazyable, predicateFn: Predicate>, ): TInput | TExtended { - try { - let beforeItem: TInput | null = null, - index = 0; - for (const item of this) { - if (predicateFn(item, index, this) && beforeItem) { - return beforeItem; - } - index++; - beforeItem = item; + let beforeItem: TInput | null = null, + index = 0; + for (const item of this) { + if (predicateFn(item, index, this) && beforeItem) { + return beforeItem; } - return simplifyLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; + beforeItem = item; } + return simplifyLazyable(defaultValue); } beforeOrFail(predicateFn: Predicate>): TInput { @@ -914,26 +753,16 @@ export class IterableCollection implements ICollection { defaultValue: Lazyable, predicateFn: Predicate>, ): TInput | TExtended { - try { - let hasMatched = false, - index = 0; - for (const item of this) { - if (hasMatched) { - return item; - } - hasMatched = predicateFn(item, index, this); - index++; - } - return simplifyLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + let hasMatched = false, + index = 0; + for (const item of this) { + if (hasMatched) { + return item; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + hasMatched = predicateFn(item, index, this); + index++; } + return simplifyLazyable(defaultValue); } afterOrFail(predicateFn: Predicate>): TInput { @@ -947,33 +776,23 @@ export class IterableCollection implements ICollection { sole( predicateFn: Predicate, TOutput>, ): TOutput { - try { - let index = 0, - matchedItem: TOutput | null = null; - for (const item of this) { - if (predicateFn(item, index, this)) { - if (matchedItem !== null) { - throw new MultipleItemsFoundCollectionError( - "Multiple items were found", - ); - } - matchedItem = item as TOutput; + let index = 0, + matchedItem: TOutput | null = null; + for (const item of this) { + if (predicateFn(item, index, this)) { + if (matchedItem !== null) { + throw new MultipleItemsFoundCollectionError( + "Multiple items were found", + ); } - index++; + matchedItem = item as TOutput; } - if (matchedItem === null) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return matchedItem; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; + } + if (matchedItem === null) { + throw new ItemNotFoundCollectionError("Item was not found"); } + return matchedItem; } nth(step: number): ICollection { @@ -981,23 +800,13 @@ export class IterableCollection implements ICollection { } count(predicateFn: Predicate>): number { - try { - let size = 0; - for (const item of this) { - if (predicateFn(item, size, this)) { - size++; - } - } - return size; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + let size = 0; + for (const item of this) { + if (predicateFn(item, size, this)) { + size++; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return size; } size(): number { @@ -1005,20 +814,10 @@ export class IterableCollection implements ICollection { } isEmpty(): boolean { - try { - for (const _ of this) { - return false; - } - return true; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + for (const _ of this) { + return false; } + return true; } isNotEmpty(): boolean { @@ -1026,77 +825,37 @@ export class IterableCollection implements ICollection { } searchFirst(predicateFn: Predicate>): number { - try { - let index = 0; - for (const item of this) { - if (predicateFn(item, index, this)) { - return index; - } - index++; - } - return -1; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + let index = 0; + for (const item of this) { + if (predicateFn(item, index, this)) { + return index; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; } + return -1; } searchLast(predicateFn: Predicate>): number { - try { - let index = 0; - let matchedIndex = -1; - for (const item of this) { - if (predicateFn(item, index, this)) { - matchedIndex = index; - } - index++; - } - return matchedIndex; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + let index = 0; + let matchedIndex = -1; + for (const item of this) { + if (predicateFn(item, index, this)) { + matchedIndex = index; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + index++; } + return matchedIndex; } forEach(callback: ForEach>): void { - try { - let index = 0; - for (const item of this) { - callback(item, index, this); - index++; - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + let index = 0; + for (const item of this) { + callback(item, index, this); + index++; } } toArray(): TInput[] { - try { - return [...this]; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return [...this]; } } diff --git a/src/collection/list-collection/list-collection.ts b/src/collection/list-collection/list-collection.ts index a9073952..638350eb 100644 --- a/src/collection/list-collection/list-collection.ts +++ b/src/collection/list-collection/list-collection.ts @@ -5,7 +5,6 @@ import { isIterable } from "@/collection/_shared"; import { type Collapse, - CollectionError, type Comparator, type Predicate, type ICollection, @@ -50,31 +49,11 @@ export class ListCollection implements ICollection { } entries(): ICollection> { - try { - return new ListCollection(this.array.entries()); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection(this.array.entries()); } keys(): ICollection { - try { - return new ListCollection(this.array.keys()); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection(this.array.keys()); } values(): ICollection { @@ -84,59 +63,29 @@ export class ListCollection implements ICollection { filter( predicateFn: Predicate, TOutput>, ): ICollection { - try { - return new ListCollection( - this.array.filter((item, index) => - predicateFn(item, index, this), - ) as TOutput[], - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection( + this.array.filter((item, index) => + predicateFn(item, index, this), + ) as TOutput[], + ); } reject( predicateFn: Predicate, TOutput>, ): ICollection> { - try { - return new ListCollection( - this.array.filter( - (item, index) => !predicateFn(item, index, this), - ) as Exclude[], - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection( + this.array.filter( + (item, index) => !predicateFn(item, index, this), + ) as Exclude[], + ); } map( mapFn: Map, TOutput>, ): ICollection { - try { - return new ListCollection( - this.array.map((item, index) => mapFn(item, index, this)), - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection( + this.array.map((item, index) => mapFn(item, index, this)), + ); } reduce(reduceFn: Reduce, TInput>): TInput; @@ -153,123 +102,71 @@ export class ListCollection implements ICollection { reduceFn: Reduce, TOutput>, initialValue?: TOutput, ): TOutput { - try { - if (initialValue === undefined && this.isEmpty()) { - throw new TypeCollectionError( - "Reduce of empty array must be inputed a initial value", - ); - } - if (initialValue !== undefined) { - return this.array.reduce( - (initialValue, item, index) => - reduceFn(initialValue, item, index, this), - initialValue, - ); - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return this.array.reduce((initialValue, item, index) => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any - const reduce = reduceFn as any; - // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call - return reduce(initialValue, item, index, this); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - }) as any; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, + if (initialValue === undefined && this.isEmpty()) { + throw new TypeCollectionError( + "Reduce of empty array must be inputed a initial value", ); } + if (initialValue !== undefined) { + return this.array.reduce( + (initialValue, item, index) => + reduceFn(initialValue, item, index, this), + initialValue, + ); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this.array.reduce((initialValue, item, index) => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any + const reduce = reduceFn as any; + // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call + return reduce(initialValue, item, index, this); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }) as any; } join(separator = ","): EnsureType { - try { - for (const item of this) { - if (typeof item !== "string") { - throw new TypeCollectionError( - "Item type is invalid must be string", - ); - } - } - return this.array.join(separator) as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + for (const item of this) { + if (typeof item !== "string") { + throw new TypeCollectionError( + "Item type is invalid must be string", + ); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return this.array.join(separator) as EnsureType; } collapse(): ICollection> { - try { - const items: TInput[] = []; - for (const item of this.array) { - if (isIterable(item)) { - items.push(...item); - } else { - items.push(item); - } - } - return new ListCollection(items as Collapse[]); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const items: TInput[] = []; + for (const item of this.array) { + if (isIterable(item)) { + items.push(...item); + } else { + items.push(item); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return new ListCollection(items as Collapse[]); } flatMap( mapFn: Map, Iterable>, ): ICollection { - try { - return new ListCollection( - this.array.flatMap((item, index) => [ - ...mapFn(item, index, this), - ]), - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection( + this.array.flatMap((item, index) => [...mapFn(item, index, this)]), + ); } change( predicateFn: Predicate, TFilterOutput>, mapFn: Map, TMapOutput>, ): ICollection> { - try { - return new ListCollection( - this.array.map((item, index) => { - if (predicateFn(item, index, this)) { - return mapFn(item as TFilterOutput, index, this); - } - return item; - }), - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection( + this.array.map((item, index) => { + if (predicateFn(item, index, this)) { + return mapFn(item as TFilterOutput, index, this); + } + return item; + }), + ); } page(page: number, pageSize: number): ICollection { @@ -308,524 +205,284 @@ export class ListCollection implements ICollection { } median(): EnsureType { - try { - if (this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", - ); - } - const nbrs = this.array.map((item) => { - if (typeof item !== "number") { - throw new TypeCollectionError( - "Item type is invalid must be number", - ); - } - return item; - }), - index = Math.floor(this.array.length / 2), - isEven = this.array.length % 2 === 0, - a = nbrs[index]; - if (a === undefined) { - throw new UnexpectedCollectionError("Is in invalid state"); - } - const b = nbrs[index - 1]; - if (isEven) { - if (b === undefined) { - throw new UnexpectedCollectionError("Is in invalid state"); - } - return ((a + b) / 2) as EnsureType; - } - return a as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, + if (this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", ); } - } - - min(): EnsureType { - try { - if (this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", - ); - } - let min = 0; - for (const item of this.array) { + const nbrs = this.array.map((item) => { if (typeof item !== "number") { throw new TypeCollectionError( "Item type is invalid must be number", ); } - if (min === 0) { - min = item; - } else if (min > item) { - min = item; - } - } - return min as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + return item; + }), + index = Math.floor(this.array.length / 2), + isEven = this.array.length % 2 === 0, + a = nbrs[index]; + if (a === undefined) { + throw new UnexpectedCollectionError("Is in invalid state"); + } + const b = nbrs[index - 1]; + if (isEven) { + if (b === undefined) { + throw new UnexpectedCollectionError("Is in invalid state"); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + return ((a + b) / 2) as EnsureType; } + return a as EnsureType; } - max(): EnsureType { - try { - if (this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", + min(): EnsureType { + if (this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", + ); + } + let min = 0; + for (const item of this.array) { + if (typeof item !== "number") { + throw new TypeCollectionError( + "Item type is invalid must be number", ); } - let max = 0; - for (const item of this.array) { - if (typeof item !== "number") { - throw new TypeCollectionError( - "Item type is invalid must be number", - ); - } - if (max === 0) { - max = item; - } else if (max < item) { - max = item; - } - } - return max as EnsureType; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (min === 0) { + min = item; + } else if (min > item) { + min = item; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return min as EnsureType; } - percentage(predicateFn: Predicate>): number { - try { - if (this.isEmpty()) { - throw new EmptyCollectionError( - "Collection is empty therby operation cannot be performed", + max(): EnsureType { + if (this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", + ); + } + let max = 0; + for (const item of this.array) { + if (typeof item !== "number") { + throw new TypeCollectionError( + "Item type is invalid must be number", ); } - return (this.count(predicateFn) / this.size()) * 100; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (max === 0) { + max = item; + } else if (max < item) { + max = item; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, + } + return max as EnsureType; + } + + percentage(predicateFn: Predicate>): number { + if (this.isEmpty()) { + throw new EmptyCollectionError( + "Collection is empty therby operation cannot be performed", ); } + return (this.count(predicateFn) / this.size()) * 100; } some( predicateFn: Predicate, TOutput>, ): boolean { - try { - return this.array.some((item, index) => - predicateFn(item, index, this), - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.array.some((item, index) => predicateFn(item, index, this)); } every( predicateFn: Predicate, TOutput>, ): boolean { - try { - return this.array.every((item, index) => - predicateFn(item, index, this), - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.array.every((item, index) => + predicateFn(item, index, this), + ); } take(limit: number): ICollection { - try { - return new ListCollection(this.array.slice(0, limit)); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection(this.array.slice(0, limit)); } takeUntil( predicateFn: Predicate>, ): ICollection { - try { - const items: TInput[] = []; - for (const [index, item] of this.array.entries()) { - if (predicateFn(item, index, this)) { - break; - } - items.push(item); + const items: TInput[] = []; + for (const [index, item] of this.array.entries()) { + if (predicateFn(item, index, this)) { + break; } - return new ListCollection(items); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + items.push(item); } + return new ListCollection(items); } takeWhile( predicateFn: Predicate>, ): ICollection { - try { - return this.takeUntil( - (...arguments_) => !predicateFn(...arguments_), - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.takeUntil((...arguments_) => !predicateFn(...arguments_)); } skip(offset: number): ICollection { - try { - return new ListCollection(this.array.slice(offset)); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection(this.array.slice(offset)); } skipUntil( predicateFn: Predicate>, ): ICollection { - try { - let hasMatched = false; - const items: TInput[] = []; - for (const [index, item] of this.array.entries()) { - if (!hasMatched) { - hasMatched = predicateFn(item, index, this); - } - if (hasMatched) { - items.push(item); - } + let hasMatched = false; + const items: TInput[] = []; + for (const [index, item] of this.array.entries()) { + if (!hasMatched) { + hasMatched = predicateFn(item, index, this); } - return new ListCollection(items); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (hasMatched) { + items.push(item); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return new ListCollection(items); } skipWhile( predicateFn: Predicate>, ): ICollection { - try { - return this.skipUntil( - (...arguments_) => !predicateFn(...arguments_), - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.skipUntil((...arguments_) => !predicateFn(...arguments_)); } when( condition: boolean, callback: Modifier, ICollection>, ): ICollection { - try { - if (condition) { - return callback(this); - } - return this as ICollection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + if (condition) { + return callback(this); } + return this as ICollection; } whenEmpty( callback: Modifier, ICollection>, ): ICollection { - try { - return this.when(this.isEmpty(), callback); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.when(this.isEmpty(), callback); } whenNot( condition: boolean, callback: Modifier, ICollection>, ): ICollection { - try { - return this.when(!condition, callback); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.when(!condition, callback); } whenNotEmpty( callback: Modifier, ICollection>, ): ICollection { - try { - return this.when(this.isNotEmpty(), callback); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.when(this.isNotEmpty(), callback); } pipe( callback: Transform, TOutput>, ): TOutput { - try { - return callback(this); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return callback(this); } tap(callback: Tap>): ICollection { - try { - callback(this); - return new ListCollection(this); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + callback(this); + return new ListCollection(this); } chunk(chunkSize: number): ICollection> { - try { - const chunks: ICollection[] = []; - for (let index = 0; index < this.size(); index += chunkSize) { - chunks.push( - new ListCollection( - this.array.slice(index, index + chunkSize), - ), - ); - } - return new ListCollection(chunks); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, + const chunks: ICollection[] = []; + for (let index = 0; index < this.size(); index += chunkSize) { + chunks.push( + new ListCollection(this.array.slice(index, index + chunkSize)), ); } + return new ListCollection(chunks); } chunkWhile( predicateFn: Predicate>, ): ICollection> { - try { - let currentChunk: ICollection = new ListCollection( - [], - ); - const chunks: ICollection[] = []; - for (const [index, item] of this.array.entries()) { - if (index === 0) { - currentChunk = currentChunk.append([item]); - } else if (predicateFn(item, index, currentChunk)) { - currentChunk = currentChunk.append([item]); - } else { - chunks.push(currentChunk); - currentChunk = new ListCollection([item]); - } - } - chunks.push(currentChunk); - return new ListCollection(chunks); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + let currentChunk: ICollection = new ListCollection([]); + const chunks: ICollection[] = []; + for (const [index, item] of this.array.entries()) { + if (index === 0) { + currentChunk = currentChunk.append([item]); + } else if (predicateFn(item, index, currentChunk)) { + currentChunk = currentChunk.append([item]); + } else { + chunks.push(currentChunk); + currentChunk = new ListCollection([item]); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + chunks.push(currentChunk); + return new ListCollection(chunks); } split(chunkAmount: number): ICollection> { - try { - const size = this.size(), - minChunkSize = Math.floor(size / chunkAmount), - restSize = size % chunkAmount, - chunkSizes = Array.from({ - length: chunkAmount, - }).fill(minChunkSize); - - for (let index = 1; index <= restSize; index++) { - const chunkIndex = (index - 1) % chunkAmount; - if (chunkSizes[chunkIndex]) { - chunkSizes[chunkIndex] = chunkSizes[chunkIndex] + 1; - } - } + const size = this.size(), + minChunkSize = Math.floor(size / chunkAmount), + restSize = size % chunkAmount, + chunkSizes = Array.from({ + length: chunkAmount, + }).fill(minChunkSize); - let end = 0, - start = 0; - const chunks: ICollection[] = []; - for (const chunkSize of chunkSizes) { - end += chunkSize; - chunks.push(new ListCollection(this.array.slice(start, end))); - start += chunkSize; + for (let index = 1; index <= restSize; index++) { + const chunkIndex = (index - 1) % chunkAmount; + if (chunkSizes[chunkIndex]) { + chunkSizes[chunkIndex] = chunkSizes[chunkIndex] + 1; } + } - return new ListCollection>(chunks); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + let end = 0, + start = 0; + const chunks: ICollection[] = []; + for (const chunkSize of chunkSizes) { + end += chunkSize; + chunks.push(new ListCollection(this.array.slice(start, end))); + start += chunkSize; } + + return new ListCollection>(chunks); } partition( predicateFn: Predicate>, ): ICollection> { - try { - const chunkA: TInput[] = [], - chunkB: TInput[] = []; - for (const [index, item] of this.array.entries()) { - if (predicateFn(item, index, this)) { - chunkA.push(item); - } else { - chunkB.push(item); - } - } - return new ListCollection>([ - new ListCollection(chunkA), - new ListCollection(chunkB), - ]); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const chunkA: TInput[] = [], + chunkB: TInput[] = []; + for (const [index, item] of this.array.entries()) { + if (predicateFn(item, index, this)) { + chunkA.push(item); + } else { + chunkB.push(item); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return new ListCollection>([ + new ListCollection(chunkA), + new ListCollection(chunkB), + ]); } sliding( chunkSize: number, step = chunkSize - 1, ): ICollection> { - try { - let chunks: ICollection> = new ListCollection< - ICollection - >([]); - if (step <= 0) { - return new ListCollection>([]); - } - for (let index = 0; index < this.size(); index += step) { - const start = index; - const end = index + chunkSize; - chunks = chunks.append([this.slice(start, end)]); - if (end >= this.size()) { - break; - } - } - return chunks; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + let chunks: ICollection> = new ListCollection< + ICollection + >([]); + if (step <= 0) { + return new ListCollection>([]); + } + for (let index = 0; index < this.size(); index += step) { + const start = index; + const end = index + chunkSize; + chunks = chunks.append([this.slice(start, end)]); + if (end >= this.size()) { + break; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return chunks; } groupBy( @@ -833,29 +490,19 @@ export class ListCollection implements ICollection { // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any item as any, ): ICollection>> { - try { - const map = new Map>(); - for (const [index, item] of this.array.entries()) { - const key = selectFn(item, index, this); - let collection: ICollection | undefined = map.get(key); - if (collection === undefined) { - collection = new ListCollection([]); - map.set(key, collection); - } - - map.set(key, collection.append([item])); + const map = new Map>(); + for (const [index, item] of this.array.entries()) { + const key = selectFn(item, index, this); + let collection: ICollection | undefined = map.get(key); + if (collection === undefined) { + collection = new ListCollection([]); + map.set(key, collection); } - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any - return new ListCollection(map as any); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + + map.set(key, collection.append([item])); } + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any + return new ListCollection(map as any); } countBy( @@ -863,28 +510,18 @@ export class ListCollection implements ICollection { // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any item as any, ): ICollection> { - try { - const map = new Map(); - for (const [index, item] of this.array.entries()) { - const key = selectFn(item, index, this); - if (!map.has(key)) { - map.set(key, 0); - } - const counter = map.get(key); - if (counter !== undefined) { - map.set(key, counter + 1); - } + const map = new Map(); + for (const [index, item] of this.array.entries()) { + const key = selectFn(item, index, this); + if (!map.has(key)) { + map.set(key, 0); } - return new ListCollection(map); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const counter = map.get(key); + if (counter !== undefined) { + map.set(key, counter + 1); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return new ListCollection(map); } unique( @@ -892,26 +529,16 @@ export class ListCollection implements ICollection { // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any item as any, ): ICollection { - try { - const set = new Set([]), - items: TInput[] = []; - for (const [index, item] of this.array.entries()) { - const item_ = selectFn(item, index, this); - if (!set.has(item_)) { - items.push(item); - } - set.add(item_); - } - return new ListCollection(items); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const set = new Set([]), + items: TInput[] = []; + for (const [index, item] of this.array.entries()) { + const item_ = selectFn(item, index, this); + if (!set.has(item_)) { + items.push(item); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + set.add(item_); } + return new ListCollection(items); } difference( @@ -920,768 +547,390 @@ export class ListCollection implements ICollection { // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any item as any, ): ICollection { - try { - const differenceCollection = new ListCollection(iterable); - return this.filter((item, index, collection) => { - return !differenceCollection.some( - (matchItem, matchIndex, matchCollection) => { - return ( - selectFn(item, index, collection) === - selectFn(matchItem, matchIndex, matchCollection) - ); - }, - ); - }); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, + const differenceCollection = new ListCollection(iterable); + return this.filter((item, index, collection) => { + return !differenceCollection.some( + (matchItem, matchIndex, matchCollection) => { + return ( + selectFn(item, index, collection) === + selectFn(matchItem, matchIndex, matchCollection) + ); + }, ); - } + }); } repeat(amount: number): ICollection { - try { - let collection: ICollection = new ListCollection( - [], - ); - for (let index = 0; index < amount; index++) { - collection = collection.append(this); - } - return collection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + let collection: ICollection = new ListCollection([]); + for (let index = 0; index < amount; index++) { + collection = collection.append(this); } + return collection; } padStart( maxLength: number, fillItems: Iterable, ): ICollection { - try { - const fillItemsArray = [...fillItems]; - const size = this.size(); - const repeat = Math.floor( - (maxLength - size) / fillItemsArray.length, - ); - const resultItemsArray: Array = []; - for (let index = 0; index < repeat; index++) { - resultItemsArray.push(...fillItemsArray); - } - const restAmount = - maxLength - (repeat * fillItemsArray.length + size); - for (let index = 0; index < restAmount; index++) { - const fillItem = fillItemsArray[index]; - if (fillItem) { - resultItemsArray.push(fillItem); - } - } - resultItemsArray.push(...this); - return new ListCollection(resultItemsArray); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const fillItemsArray = [...fillItems]; + const size = this.size(); + const repeat = Math.floor((maxLength - size) / fillItemsArray.length); + const resultItemsArray: Array = []; + for (let index = 0; index < repeat; index++) { + resultItemsArray.push(...fillItemsArray); + } + const restAmount = maxLength - (repeat * fillItemsArray.length + size); + for (let index = 0; index < restAmount; index++) { + const fillItem = fillItemsArray[index]; + if (fillItem) { + resultItemsArray.push(fillItem); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + resultItemsArray.push(...this); + return new ListCollection(resultItemsArray); } padEnd( maxLength: number, fillItems: Iterable, ): ICollection { - try { - const fillItemsArray = [...fillItems]; - const size = this.size(); - const repeat = Math.floor( - (maxLength - size) / fillItemsArray.length, - ); - const resultItemsArray: Array = []; - for (let index = 0; index < repeat; index++) { - resultItemsArray.push(...fillItemsArray); - } - const restAmount = - maxLength - (repeat * fillItemsArray.length + size); - for (let index = 0; index < restAmount; index++) { - const fillItem = fillItemsArray[index]; - if (fillItem) { - resultItemsArray.push(fillItem); - } - } - resultItemsArray.unshift(...this); - return new ListCollection(resultItemsArray); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const fillItemsArray = [...fillItems]; + const size = this.size(); + const repeat = Math.floor((maxLength - size) / fillItemsArray.length); + const resultItemsArray: Array = []; + for (let index = 0; index < repeat; index++) { + resultItemsArray.push(...fillItemsArray); + } + const restAmount = maxLength - (repeat * fillItemsArray.length + size); + for (let index = 0; index < restAmount; index++) { + const fillItem = fillItemsArray[index]; + if (fillItem) { + resultItemsArray.push(fillItem); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + resultItemsArray.unshift(...this); + return new ListCollection(resultItemsArray); } slice(start?: number, end?: number): ICollection { - try { - return new ListCollection(this.array.slice(start, end)); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection(this.array.slice(start, end)); } prepend( iterable: Iterable, ): ICollection { - try { - return new ListCollection([...iterable, ...this.array]); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection([...iterable, ...this.array]); } append( iterable: Iterable, ): ICollection { - try { - return new ListCollection([...this.array, ...iterable]); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection([...this.array, ...iterable]); } insertBefore( predicateFn: Predicate>, iterable: Iterable, ): ICollection { - try { - const index = this.array.findIndex((item, index) => - predicateFn(item, index, this), - ); - if (index === -1) { - return new ListCollection(this.array); - } - const newArray = [...this.array] as Array; - newArray.splice(index, 0, ...iterable); - return new ListCollection(newArray); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + const index = this.array.findIndex((item, index) => + predicateFn(item, index, this), + ); + if (index === -1) { + return new ListCollection(this.array); } + const newArray = [...this.array] as Array; + newArray.splice(index, 0, ...iterable); + return new ListCollection(newArray); } insertAfter( predicateFn: Predicate>, iterable: Iterable, ): ICollection { - try { - const index = this.array.findIndex((item, index) => - predicateFn(item, index, this), - ); - if (index === -1) { - return new ListCollection(this.array) as ICollection< - TInput | TExtended - >; - } - const firstPart = this.array.slice(0, index + 1), - lastPart = this.array.slice(index + 1); - return new ListCollection([ - ...firstPart, - ...iterable, - ...lastPart, - ]) as ICollection; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + const index = this.array.findIndex((item, index) => + predicateFn(item, index, this), + ); + if (index === -1) { + return new ListCollection(this.array) as ICollection< + TInput | TExtended + >; + } + const firstPart = this.array.slice(0, index + 1), + lastPart = this.array.slice(index + 1); + return new ListCollection([ + ...firstPart, + ...iterable, + ...lastPart, + ]) as ICollection; } crossJoin( iterable: Iterable, ): ICollection> { - try { - const array: Array> = [ - [...this], - [...iterable], - ] - .reduce>>( - (a, b) => { - return a - .map((x) => { - return b.map((y) => { - return [...x, y]; - }); - }) - .reduce>>( - (c, b) => [...c, ...b], - [], - ); - }, - [[] as Array], - ) - .map((combination) => { - // Flatting the array - return combination.reduce>( - (a, b) => { - return [ - ...a, - ...(isIterable(b) ? b : [b]), - ] as Array; - }, - [], - ); - }); + const array: Array> = [ + [...this], + [...iterable], + ] + .reduce>>( + (a, b) => { + return a + .map((x) => { + return b.map((y) => { + return [...x, y]; + }); + }) + .reduce>>( + (c, b) => [...c, ...b], + [], + ); + }, + [[] as Array], + ) + .map((combination) => { + // Flatting the array + return combination.reduce>((a, b) => { + return [...a, ...(isIterable(b) ? b : [b])] as Array< + TInput | TExtended + >; + }, []); + }); - return new ListCollection( - array as Array>, - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection( + array as Array>, + ); } zip( iterable: Iterable, ): ICollection> { - try { - const iterableArray = [...iterable]; - let size = iterableArray.length; - if (size > this.size()) { - size = this.size(); - } - const items: RecordItem[] = []; - for (let index = 0; index < size; index++) { - const itemA = this.array[index], - itemB = iterableArray[index]; - if (itemA === undefined || itemB === undefined) { - continue; - } - items.push([itemA, itemB]); - } - return new ListCollection(items); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const iterableArray = [...iterable]; + let size = iterableArray.length; + if (size > this.size()) { + size = this.size(); + } + const items: RecordItem[] = []; + for (let index = 0; index < size; index++) { + const itemA = this.array[index], + itemB = iterableArray[index]; + if (itemA === undefined || itemB === undefined) { + continue; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + items.push([itemA, itemB]); } + return new ListCollection(items); } sort(comparator?: Comparator): ICollection { - try { - return new ListCollection(this.array.sort(comparator)); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection(this.array.sort(comparator)); } reverse(_chunkSize?: number): ICollection { - try { - return new ListCollection([...this.array].reverse()); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return new ListCollection([...this.array].reverse()); } shuffle(mathRandom = Math.random): ICollection { - try { - const newArray = [...this.array]; - for (let i = newArray.length - 1; i > 0; i--) { - const j = Math.floor(mathRandom() * (i + 1)); - const temp = newArray[i]; - if (newArray[j] !== undefined) { - newArray[i] = newArray[j]; - } - if (temp !== undefined) { - newArray[j] = temp; - } + const newArray = [...this.array]; + for (let i = newArray.length - 1; i > 0; i--) { + const j = Math.floor(mathRandom() * (i + 1)); + const temp = newArray[i]; + if (newArray[j] !== undefined) { + newArray[i] = newArray[j]; } - return new ListCollection(newArray); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (temp !== undefined) { + newArray[j] = temp; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return new ListCollection(newArray); } first( predicateFn?: Predicate, TOutput>, ): TOutput | null { - try { - return this.firstOr(null, predicateFn); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.firstOr(null, predicateFn); } firstOr( defaultValue: Lazyable, predicateFn?: Predicate, TOutput>, ): TOutput | TExtended { - try { - if (predicateFn) { - for (const [index, item] of this.array.entries()) { - if (predicateFn(item, index, this)) { - return item as TOutput; - } - } - } else { - const firstItem = this.array[0]; - if (firstItem) { - return firstItem as TOutput; + if (predicateFn) { + for (const [index, item] of this.array.entries()) { + if (predicateFn(item, index, this)) { + return item as TOutput; } } - return simplifyLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + } else { + const firstItem = this.array[0]; + if (firstItem) { + return firstItem as TOutput; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return simplifyLazyable(defaultValue); } firstOrFail( predicateFn?: Predicate, TOutput>, ): TOutput { - try { - const item = this.first(predicateFn); - if (item === null) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return item; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + const item = this.first(predicateFn); + if (item === null) { + throw new ItemNotFoundCollectionError("Item was not found"); } + return item; } last( predicateFn?: Predicate, TOutput>, ): TOutput | null { - try { - return this.lastOr(null, predicateFn); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.lastOr(null, predicateFn); } lastOr( defaultValue: Lazyable, predicateFn?: Predicate, TOutput>, ): TOutput | TExtended { - try { - if (predicateFn) { - let matchedItem: TOutput | null = null; - for (const [index, item] of this.array.entries()) { - if (predicateFn(item, index, this)) { - matchedItem = item as TOutput; - } - } - if (matchedItem) { - return matchedItem; - } - } else { - const lastItem = this.array.at(-1); - if (lastItem) { - return lastItem as TOutput; + if (predicateFn) { + let matchedItem: TOutput | null = null; + for (const [index, item] of this.array.entries()) { + if (predicateFn(item, index, this)) { + matchedItem = item as TOutput; } } - return simplifyLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + if (matchedItem) { + return matchedItem; + } + } else { + const lastItem = this.array.at(-1); + if (lastItem) { + return lastItem as TOutput; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return simplifyLazyable(defaultValue); } lastOrFail( predicateFn?: Predicate, TOutput>, ): TOutput { - try { - const item = this.last(predicateFn); - if (item === null) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return item; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + const item = this.last(predicateFn); + if (item === null) { + throw new ItemNotFoundCollectionError("Item was not found"); } + return item; } before(predicateFn: Predicate>): TInput | null { - try { - return this.beforeOr(null, predicateFn); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.beforeOr(null, predicateFn); } beforeOr( defaultValue: Lazyable, predicateFn: Predicate>, ): TInput | TExtended { - try { - for (const [index, item] of this.array.entries()) { - const beforeItem = this.array[index - 1]; - if ( - predicateFn(item, index, this) && - beforeItem !== undefined - ) { - return beforeItem; - } - } - return simplifyLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + for (const [index, item] of this.array.entries()) { + const beforeItem = this.array[index - 1]; + if (predicateFn(item, index, this) && beforeItem !== undefined) { + return beforeItem; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return simplifyLazyable(defaultValue); } beforeOrFail(predicateFn: Predicate>): TInput { - try { - const item = this.before(predicateFn); - if (item === null) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return item; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + const item = this.before(predicateFn); + if (item === null) { + throw new ItemNotFoundCollectionError("Item was not found"); } + return item; } after(predicateFn: Predicate>): TInput | null { - try { - return this.afterOr(null, predicateFn); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.afterOr(null, predicateFn); } afterOr( defaultValue: Lazyable, predicateFn: Predicate>, ): TInput | TExtended { - try { - for (const [index, item] of this.array.entries()) { - const beforeItem = this.array[index + 1]; - if ( - predicateFn(item, index, this) && - beforeItem !== undefined - ) { - return beforeItem; - } - } - return simplifyLazyable(defaultValue); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + for (const [index, item] of this.array.entries()) { + const beforeItem = this.array[index + 1]; + if (predicateFn(item, index, this) && beforeItem !== undefined) { + return beforeItem; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return simplifyLazyable(defaultValue); } afterOrFail(predicateFn: Predicate>): TInput { - try { - const item = this.after(predicateFn); - if (item === null) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return item; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + const item = this.after(predicateFn); + if (item === null) { + throw new ItemNotFoundCollectionError("Item was not found"); } + return item; } sole( predicateFn: Predicate, TOutput>, ): TOutput { - try { - const matchedItems: TInput[] = []; - for (const [index, item] of this.array.entries()) { - if (predicateFn(item, index, this)) { - matchedItems.push(item); - } - if (matchedItems.length > 1) { - throw new MultipleItemsFoundCollectionError( - "Multiple items were found", - ); - } - } - const [matchedItem] = matchedItems; - if (matchedItem === undefined) { - throw new ItemNotFoundCollectionError("Item was not found"); - } - return matchedItem as TOutput; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + const matchedItems: TInput[] = []; + for (const [index, item] of this.array.entries()) { + if (predicateFn(item, index, this)) { + matchedItems.push(item); + } + if (matchedItems.length > 1) { + throw new MultipleItemsFoundCollectionError( + "Multiple items were found", + ); } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + const [matchedItem] = matchedItems; + if (matchedItem === undefined) { + throw new ItemNotFoundCollectionError("Item was not found"); + } + return matchedItem as TOutput; } nth(step: number): ICollection { - try { - return this.filter((_item, index) => index % step === 0); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.filter((_item, index) => index % step === 0); } count(predicateFn: Predicate>): number { - try { - return this.filter(predicateFn).size(); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.filter(predicateFn).size(); } size(): number { - try { - return this.array.length; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.array.length; } isEmpty(): boolean { - try { - return this.array.length === 0; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.array.length === 0; } isNotEmpty(): boolean { - try { - return this.array.length !== 0; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.array.length !== 0; } searchFirst(predicateFn: Predicate>): number { - try { - return this.array.findIndex((item, index) => - predicateFn(item, index, this), - ); - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return this.array.findIndex((item, index) => + predicateFn(item, index, this), + ); } searchLast(predicateFn: Predicate>): number { - try { - let matchedIndex = -1; - for (const [index, item] of this.array.entries()) { - if (predicateFn(item, index, this)) { - matchedIndex = index; - } - } - return matchedIndex; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; + let matchedIndex = -1; + for (const [index, item] of this.array.entries()) { + if (predicateFn(item, index, this)) { + matchedIndex = index; } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); } + return matchedIndex; } forEach(callback: ForEach>): void { - try { - for (const [index, item] of this.array.entries()) { - callback(item, index, this); - } - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); + for (const [index, item] of this.array.entries()) { + callback(item, index, this); } } toArray(): TInput[] { - try { - return [...this.array]; - } catch (error: unknown) { - if (error instanceof CollectionError) { - throw error; - } - throw new UnexpectedCollectionError( - `Unexpected error "${String(error)}" occured`, - error, - ); - } + return [...this.array]; } } diff --git a/src/contracts/collection/_shared.ts b/src/contracts/collection/_shared.ts index da49af74..74501455 100644 --- a/src/contracts/collection/_shared.ts +++ b/src/contracts/collection/_shared.ts @@ -114,7 +114,7 @@ export type AsyncPredicate_ = ( item: TInput, index: number, collection: TCollection, -) => Promise; +) => PromiseLike; export type AsyncPredicate< TInput, @@ -129,7 +129,7 @@ export type AsyncReduce_ = ( item: TInput, index: number, collection: TCollection, -) => Promise; +) => PromiseLike; export type AsyncReduce = | AsyncReduce_ @@ -139,7 +139,7 @@ export type AsyncMap_ = ( item: TInput, index: number, collection: TCollection, -) => Promise; +) => PromiseLike; export type AsyncMap = | AsyncMap_ @@ -149,7 +149,7 @@ export type AsyncForEach_ = ( item: TInput, index: number, collection: TCollection, -) => Promise; +) => PromiseLike; export type AsyncForEach = | ForEach @@ -157,19 +157,21 @@ export type AsyncForEach = export type AsyncModifier_ = ( collection: TInput, -) => Promise; +) => PromiseLike; export type AsyncModifier = | Modifier | AsyncModifier_; -export type AsyncTap_ = (collection: TCollection) => Promise; +export type AsyncTap_ = ( + collection: TCollection, +) => PromiseLike; export type AsyncTap = Tap | AsyncTap_; export type AsyncTransform_ = ( value: TInput, -) => Promise; +) => PromiseLike; export type AsyncTransform = | Transform diff --git a/src/contracts/collection/async-collection.contract.ts b/src/contracts/collection/async-collection.contract.ts index 42b7a7b6..41de1dd2 100644 --- a/src/contracts/collection/async-collection.contract.ts +++ b/src/contracts/collection/async-collection.contract.ts @@ -33,6 +33,7 @@ import type { EnsureType, AsyncIterableValue, } from "@/_shared/types"; +import type { TimeSpan } from "@/_module"; export type AsyncCollapse = TValue extends | Array @@ -139,16 +140,16 @@ export type IAsyncCollection = AsyncIterable & { */ reduce( reduceFn: AsyncReduce, TInput>, - ): Promise; + ): PromiseLike; reduce( reduceFn: AsyncReduce, TInput>, // eslint-disable-next-line @typescript-eslint/unified-signatures initialValue: TInput, - ): Promise; + ): PromiseLike; reduce( reduceFn: AsyncReduce, TOutput>, initialValue: TOutput, - ): Promise; + ): PromiseLike; /** * The join method joins the collection's items with separator . An error will be thrown when if a none string item is encounterd. @@ -166,7 +167,7 @@ export type IAsyncCollection = AsyncIterable & { * await collection.map(item => item.toString()).join("_"); * // "1_2_3_4" */ - join(separator?: string): Promise>; + join(separator?: string): PromiseLike>; /** * The collapse method collapses a collection of iterables into a single, flat collection. @@ -238,7 +239,7 @@ export type IAsyncCollection = AsyncIterable & { * @throws {TypeCollectionError} {@link TypeCollectionError} * @throws {EmptyCollectionError} {@link EmptyCollectionError} */ - sum(): Promise>; + sum(): PromiseLike>; /** * The average method returns the average of all items in the collection. If the collection includes other than number items an error will be thrown. @@ -253,7 +254,7 @@ export type IAsyncCollection = AsyncIterable & { * @throws {TypeCollectionError} {@link TypeCollectionError} * @throws {EmptyCollectionError} {@link EmptyCollectionError} */ - average(): Promise>; + average(): PromiseLike>; /** * The median method returns the median of all items in the collection. If the collection includes other than number items an error will be thrown. @@ -268,7 +269,7 @@ export type IAsyncCollection = AsyncIterable & { * @throws {TypeCollectionError} {@link TypeCollectionError} * @throws {EmptyCollectionError} {@link EmptyCollectionError} */ - median(): Promise>; + median(): PromiseLike>; /** * The min method returns the min of all items in the collection. If the collection includes other than number items an error will be thrown. @@ -283,7 +284,7 @@ export type IAsyncCollection = AsyncIterable & { * @throws {TypeCollectionError} {@link TypeCollectionError} * @throws {EmptyCollectionError} {@link EmptyCollectionError} */ - min(): Promise>; + min(): PromiseLike>; /** * The max method returns the max of all items in the collection. If the collection includes other than number items an error will be thrown. @@ -298,7 +299,7 @@ export type IAsyncCollection = AsyncIterable & { * @throws {TypeCollectionError} {@link TypeCollectionError} * @throws {EmptyCollectionError} {@link EmptyCollectionError} */ - max(): Promise>; + max(): PromiseLike>; /** * The percentage method may be used to quickly determine the percentage of items in the collection that pass predicateFn. @@ -314,7 +315,7 @@ export type IAsyncCollection = AsyncIterable & { */ percentage( predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The some method determines whether at least one item in the collection matches predicateFn. @@ -329,7 +330,7 @@ export type IAsyncCollection = AsyncIterable & { */ some( predicateFn: AsyncPredicate, TOutput>, - ): Promise; + ): PromiseLike; /** * The every method determines whether all items in the collection matches predicateFn. @@ -344,7 +345,7 @@ export type IAsyncCollection = AsyncIterable & { */ every( predicateFn: AsyncPredicate, TOutput>, - ): Promise; + ): PromiseLike; /** * The take method takes the first limit items. @@ -539,7 +540,7 @@ export type IAsyncCollection = AsyncIterable & { */ pipe( callback: AsyncTransform, TOutput>, - ): Promise; + ): PromiseLike; /** * The tap method passes a copy of the original collection to callback, allowing you to do something with the items while not affecting the original collection. @@ -1080,7 +1081,7 @@ export type IAsyncCollection = AsyncIterable & { */ first( predicateFn?: AsyncPredicate, TOutput>, - ): Promise; + ): PromiseLike; /** * The firstOr method returns the first item in the collection that passes predicateFn @@ -1115,7 +1116,7 @@ export type IAsyncCollection = AsyncIterable & { firstOr( defaultValue: AsyncLazyable, predicateFn?: AsyncPredicate, TOutput>, - ): Promise; + ): PromiseLike; /** * The firstOrFail method returns the first item in the collection that passes predicateFn . @@ -1144,7 +1145,7 @@ export type IAsyncCollection = AsyncIterable & { */ firstOrFail( predicateFn?: AsyncPredicate, TOutput>, - ): Promise; + ): PromiseLike; /** * The last method returns the last item in the collection that passes predicateFn . @@ -1173,7 +1174,7 @@ export type IAsyncCollection = AsyncIterable & { */ last( predicateFn?: AsyncPredicate, TOutput>, - ): Promise; + ): PromiseLike; /** * The lastOr method returns the last item in the collection that passes predicateFn . @@ -1208,7 +1209,7 @@ export type IAsyncCollection = AsyncIterable & { lastOr( defaultValue: AsyncLazyable, predicateFn?: AsyncPredicate, TOutput>, - ): Promise; + ): PromiseLike; /** * The lastOrFail method returns the last item in the collection that passes predicateFn . @@ -1237,7 +1238,7 @@ export type IAsyncCollection = AsyncIterable & { */ lastOrFail( predicateFn?: AsyncPredicate, TOutput>, - ): Promise; + ): PromiseLike; /** * The before method returns the item that comes before the first item that matches predicateFn. @@ -1259,7 +1260,7 @@ export type IAsyncCollection = AsyncIterable & { */ before( predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The beforeOr method returns the item that comes before the first item that matches predicateFn. @@ -1288,7 +1289,7 @@ export type IAsyncCollection = AsyncIterable & { beforeOr( defaultValue: AsyncLazyable, predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The beforeOrFail method returns the item that comes before the first item that matches predicateFn. @@ -1311,7 +1312,7 @@ export type IAsyncCollection = AsyncIterable & { */ beforeOrFail( predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The after method returns the item that comes after the first item that matches predicateFn. @@ -1333,7 +1334,7 @@ export type IAsyncCollection = AsyncIterable & { */ after( predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The afterOr method returns the item that comes after the first item that matches predicateFn. @@ -1362,7 +1363,7 @@ export type IAsyncCollection = AsyncIterable & { afterOr( defaultValue: AsyncLazyable, predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The afterOrFail method returns the item that comes after the first item that matches predicateFn. @@ -1385,7 +1386,7 @@ export type IAsyncCollection = AsyncIterable & { */ afterOrFail( predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The sole method returns the first item in the collection that passes predicateFn, but only if predicateFn matches exactly one item. @@ -1415,7 +1416,7 @@ export type IAsyncCollection = AsyncIterable & { */ sole( predicateFn: AsyncPredicate, TOutput>, - ): Promise; + ): PromiseLike; /** * The nth method creates a new collection consisting of every n-th item. @@ -1441,28 +1442,28 @@ export type IAsyncCollection = AsyncIterable & { */ count( predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The size returns the size of the collection. * @throws {CollectionError} {@link CollectionError} * @throws {UnexpectedCollectionError} {@link UnexpectedCollectionError} */ - size(): Promise; + size(): PromiseLike; /** * The isEmpty returns true if the collection is empty. * @throws {CollectionError} {@link CollectionError} * @throws {UnexpectedCollectionError} {@link UnexpectedCollectionError} */ - isEmpty(): Promise; + isEmpty(): PromiseLike; /** * The isNotEmpty returns true if the collection is not empty. * @throws {CollectionError} {@link CollectionError} * @throws {UnexpectedCollectionError} {@link UnexpectedCollectionError} */ - isNotEmpty(): Promise; + isNotEmpty(): PromiseLike; /** * The searchFirst return the index of the first item that matches predicateFn. @@ -1477,7 +1478,7 @@ export type IAsyncCollection = AsyncIterable & { */ searchFirst( predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The searchLast return the index of the last item that matches predicateFn. @@ -1492,7 +1493,7 @@ export type IAsyncCollection = AsyncIterable & { */ searchLast( predicateFn: AsyncPredicate>, - ): Promise; + ): PromiseLike; /** * The forEach method iterates through all items in the collection. @@ -1501,17 +1502,17 @@ export type IAsyncCollection = AsyncIterable & { */ forEach( callback: AsyncForEach>, - ): Promise; + ): PromiseLike; /** * The toArray method converts the collection to a new array. * @throws {CollectionError} {@link CollectionError} * @throws {UnexpectedCollectionError} {@link UnexpectedCollectionError} */ - toArray(): Promise; + toArray(): PromiseLike; /** - * The delay method will delay collection such that each value is returned after the specified number of seconds. + * The delay method will add delay between each iteration. * This method is especially useful for situations where you may be interacting with external APIs that rate limit incoming requests: * @example * import { AsyncIterableCollection } from "@daiso-tech/core";; @@ -1522,12 +1523,26 @@ export type IAsyncCollection = AsyncIterable & { * const collection = new AsyncIterableCollection(apiIterator); * await collection.delay(1000).forEach(user => console.log(user)) */ - delay(timeInMs: number): IAsyncCollection; + delay(time: TimeSpan): IAsyncCollection; - abort(signal: AbortSignal): IAsyncCollection; + /** + * The abort method will abort iteration of the collection by passing {@link AbortSignal}. + * @example + * import { AsyncIterableCollection } from "@daiso-tech/core";; + * + * // An iterator that will fetch all users from a specific api + * class ApiIterator implements AsyncIterable { ... } + * const apiIterator = new ApiIterator(); + * const collection = new AsyncIterableCollection(apiIterator); + * await collection.delay(1000).forEach(user => console.log(user)) + */ + takeUntilAbort( + abortSignal: AbortSignal, + shouldThrow?: boolean, + ): IAsyncCollection; /** - * The timeout method returns a new collection that will iterate values until the specified time. + * The timeout method returns a new collection that will iterate values until the specified time. * After that time, the collection will then stop iterating: * @example * import { AsyncIterableCollection } from "@daiso-tech/core";; @@ -1545,5 +1560,8 @@ export type IAsyncCollection = AsyncIterable & { * .timeout(1000) * .forEach(nbr => console.log(nbr)) */ - timeout(timeInMs: number): IAsyncCollection; + takeUntilTimeout( + timeInMs: TimeSpan, + shouldThrow?: boolean, + ): IAsyncCollection; };