Skip to content

Instantly share code, notes, and snippets.

View MattiasBuelens's full-sized avatar

Mattias Buelens MattiasBuelens

View GitHub Profile
@MattiasBuelens
MattiasBuelens / readable-stream-async-iterator-polyfill.js
Created September 1, 2023 09:17
ReadableStream async iterator polyfill
/**
* A polyfill for `ReadableStream.protototype[Symbol.asyncIterator]`,
* aligning as closely as possible to the specification.
*
* @see https://streams.spec.whatwg.org/#rs-asynciterator
* @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#async_iteration
*/
ReadableStream.prototype.values ??= function({ preventCancel = false } = {}) {
const reader = this.getReader();
return {
@MattiasBuelens
MattiasBuelens / tee-async-iterator.ts
Last active November 30, 2023 02:14
Teeing an async iterator
/**
* Like ReadableStream.tee(), but for any async iterable.
* https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/tee
*
* See: MattiasBuelens/web-streams-polyfill#80
*/
/// <reference lib="esnext" />
interface QueueNode<T> {
value: T;
@MattiasBuelens
MattiasBuelens / delay.ts
Created September 12, 2019 18:18
raceAbort example
function delay(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 100));
}
function abortableDelay(signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal.aborted) {
return reject(new DOMException('Aborted', 'AbortError'));
}
const onAbort = () => {
@MattiasBuelens
MattiasBuelens / streams.ts
Created June 27, 2018 18:55
Workaround for WHATWG streams in TypeScript
import {
ReadableStream as WhatWGReadableStream,
TransformStream as WhatWGTransformStream,
WritableStream as WhatWGWritableStream
} from 'whatwg-streams';
export type ReadableStream<R> = WhatWGReadableStream<R>;
export const ReadableStream: typeof WhatWGReadableStream = (self as any).ReadableStream;
export type WritableStream<W> = WhatWGWritableStream<W>;