-
Notifications
You must be signed in to change notification settings - Fork 18
/
fromAsync.ts
36 lines (32 loc) · 1.37 KB
/
fromAsync.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { ErrorString, InvalidOperationException } from "../../shared"
import { IAsyncEnumerable } from "../../types"
import { BasicAsyncEnumerable } from "../BasicAsyncEnumerable"
type FromAsyncFunc = {
/**
* Converts the input array of promises to an async iterable
* @param promises Array of Promises to Convert to an IAsyncEnumerable<T>
* @throws {InvalidOperationException} No Elements in the Promises Array
* @returns IAsyncEnumerable<T>
*/
<TSource>(promises: Promise<TSource>[]): IAsyncEnumerable<TSource>
/**
* Converts the input method to an async iterable
* @param asyncIterable Function which returns an AsyncIterableIterator<TSource>
* @returns IAsyncEnumerable<T>
*/
<TSource>(asyncIterable: () => AsyncIterableIterator<TSource>): IAsyncEnumerable<TSource>
}
export const fromAsync: FromAsyncFunc = <TSource>(promisesOrIterable: Promise<TSource>[] | (() => AsyncIterableIterator<TSource>)) => {
if (Array.isArray(promisesOrIterable)) {
if (promisesOrIterable.length === 0) {
throw new InvalidOperationException(ErrorString.NoElements)
}
return new BasicAsyncEnumerable(async function*() {
for await (const value of promisesOrIterable) {
yield value
}
})
} else {
return new BasicAsyncEnumerable(promisesOrIterable)
}
}