-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathcreate.ts
More file actions
36 lines (30 loc) · 1.16 KB
/
create.ts
File metadata and controls
36 lines (30 loc) · 1.16 KB
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 { AsyncIterableX } from './asynciterablex.js';
import { throwIfAborted } from '../aborterror.js';
class AnonymousAsyncIterable<T> extends AsyncIterableX<T> {
private _fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>;
constructor(fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>) {
super();
this._fn = fn;
}
async *[Symbol.asyncIterator](signal?: AbortSignal) {
throwIfAborted(signal);
const it = await this._fn(signal);
for await (const item of {
[Symbol.asyncIterator]: () => it,
}) {
yield item;
}
}
}
/**
* Creates a new iterable using the specified function implementing the members of AsyncIterable
*
* @template T The type of the elements returned by the enumerable sequence.
* @param {((signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>)} fn The function that creates the [Symbol.asyncIterator]() method
* @returns {AsyncIterableX<T>} A new async-iterable instance.
*/
export function create<T>(
fn: (signal?: AbortSignal) => AsyncIterator<T> | Promise<AsyncIterator<T>>
): AsyncIterableX<T> {
return new AnonymousAsyncIterable(fn);
}