-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Open
Labels
Description
available in firefox since 117 and node since 20.6.0, but chrome support for this has stalled https://issues.chromium.org/issues/40267032
typescript polyfill meeting spec https://streams.spec.whatwg.org/#readable-stream-from-iterable
declare global {
interface ReadableStream<R = any> {
from<T>(iterable: Iterable<T> | AsyncIterable<T>): ReadableStream<T>;
}
}
if (!('from' in ReadableStream)) {
Object.defineProperty(ReadableStream, 'from', {
enumerable: true,
configurable: true,
writable: true,
value: from,
});
}
function from<T>(iterable: Iterable<T> | AsyncIterable<T>): ReadableStream<T> {
const iterator = (
Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator] : iterable[Symbol.iterator]
)();
return new ReadableStream(
{
async pull(cont) {
const result = await iterator.next();
if (result.done) {
cont.close();
} else {
cont.enqueue(result.value);
}
},
async cancel(reason) {
await iterator.return?.(reason);
},
},
{ highWaterMark: 0 },
);
}