|
| 1 | +export interface SidechainOpts { |
| 2 | + /** |
| 3 | + * If true (default), only emits the last received value when the sidechain |
| 4 | + * triggers. Otherwise buffers and emits *all* received values since the |
| 5 | + * last time the sidechain triggered. |
| 6 | + * |
| 7 | + * @defaultValue true |
| 8 | + */ |
| 9 | + lastOnly: boolean; |
| 10 | +} |
| 11 | + |
| 12 | +export function sidechain<T>( |
| 13 | + src: AsyncIterable<T>, |
| 14 | + side: AsyncIterable<boolean>, |
| 15 | + opts: Partial<SidechainOpts> & { lastOnly: false } |
| 16 | +): AsyncIterableIterator<T[]>; |
| 17 | +export function sidechain<T>( |
| 18 | + src: AsyncIterable<T>, |
| 19 | + side: AsyncIterable<boolean>, |
| 20 | + opts?: Partial<SidechainOpts> |
| 21 | +): AsyncIterableIterator<T>; |
| 22 | +export async function* sidechain<T>( |
| 23 | + src: AsyncIterable<T>, |
| 24 | + side: AsyncIterable<boolean>, |
| 25 | + opts?: Partial<SidechainOpts> |
| 26 | +) { |
| 27 | + const { lastOnly = true } = opts || {}; |
| 28 | + const $iter = src[Symbol.asyncIterator](); |
| 29 | + const $side = side[Symbol.asyncIterator](); |
| 30 | + const promises: Promise<[IteratorResult<any>, boolean?]>[] = [ |
| 31 | + $iter.next().then((res) => [res]), |
| 32 | + $side.next().then((res) => [res, true]), |
| 33 | + ]; |
| 34 | + let buf: T[] = []; |
| 35 | + while (true) { |
| 36 | + const [res, side] = await Promise.any(promises); |
| 37 | + if (res.done) return; |
| 38 | + if (side) { |
| 39 | + promises[1] = $side.next().then((res) => [res, true]); |
| 40 | + if (!buf.length) continue; |
| 41 | + if (lastOnly) { |
| 42 | + yield buf[0]; |
| 43 | + buf.length = 0; |
| 44 | + } else { |
| 45 | + yield buf; |
| 46 | + buf = []; |
| 47 | + } |
| 48 | + } else { |
| 49 | + promises[0] = $iter.next().then((res) => [res]); |
| 50 | + if (lastOnly) buf[0] = res.value; |
| 51 | + else buf.push(res.value); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments