This repository was archived by the owner on Feb 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoIterable.ts
46 lines (45 loc) · 1.7 KB
/
toIterable.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
37
38
39
40
41
42
43
44
45
46
import { isAsyncIterable, isIterable } from "@vangware/predicates";
import type { IsomorphicIterable } from "@vangware/types";
import { createIterableIterator } from "./createIterableIterator.js";
import type { ReadOnlyAsyncIterable } from "./types/ReadOnlyAsyncIterable.js";
import type { ReadOnlyAsyncIterableIterator } from "./types/ReadOnlyAsyncIterableIterator.js";
import type { ReadOnlyIterableIterator } from "./types/ReadOnlyIterableIterator.js";
/**
* Takes a value, iterable or asynchronous iterable and yields it.
*
* @category Generators
* @example
* ```typescript
* const iterable = toIterable(1);
* const iterator = getIterator(iterable);
* iterator.next(); // { value: 1, done: false }
* iterator.next(); // { value: undefined, done: true }
* ```
* @see {@link createIterableIterator}
* @see {@link ReadOnlyAsyncIterable}
* @see {@link ReadOnlyAsyncIterableIterator}
* @see {@link ReadOnlyIterableIterator}
*
* @template ValueOrIterable Generic of value or iterable to yield.
* @param valueOrIterable Vale or iterable to yield.
* @returns Yielded item or iterable.
*/
export const toIterable = <const ValueOrIterable>(
valueOrIterable: ValueOrIterable,
) =>
createIterableIterator(
isAsyncIterable(valueOrIterable)
? async function* () {
yield* valueOrIterable;
}
: function* () {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
isIterable(valueOrIterable)
? yield* valueOrIterable
: yield valueOrIterable;
},
) as ValueOrIterable extends IsomorphicIterable<infer Item>
? Item extends ReadOnlyAsyncIterable<Item>
? ReadOnlyAsyncIterableIterator<Item>
: ReadOnlyIterableIterator<Item>
: ReadOnlyIterableIterator<ValueOrIterable>;