import { AsyncIterableX } from '../asynciterablex' ; import { isAsyncIterable } from '../../util/isiterable' ; import { MonoTypeOperatorAsyncFunction } from '../../interfaces' ; import { wrapWithAbort } from './withabort' ; import { throwIfAborted } from '../../aborterror' ; export class FlattenAsyncIterable < TSource > extends AsyncIterableX < TSource > { private _source : AsyncIterable < TSource > ; private _depth : number ; constructor ( source , depth ) { super ( ) ; this . _source = source ; this . _depth = depth ; } private async * _flatten ( source , depth , signal ? ) { if ( depth === 0 ) { for await ( const item of wrapWithAbort ( source , signal ) ) { yield item ; } return undefined ; } for await ( const item of wrapWithAbort ( source , signal ) ) { if ( isAsyncIterable ( item ) ) { for await ( const innerItem of this . _flatten ( item , depth - 1 , signal ) ) { yield innerItem ; } } else { yield item ; } } } [ Symbol . asyncIterator ] ( signal ? ) { throwIfAborted ( signal ) ; return this . _flatten ( this . _source , this . _depth , signal ) [ Symbol . asyncIterator ] ( ) ; } } template T param { number } depth returns { MonoTypeOperatorAsyncFunction < T > } export function flat < T > ( depth = Infinity ) { return function flattenOperatorFunction ( source ) : AsyncIterableX < T > { return new FlattenAsyncIterable < T > ( source , depth ) ; } ; }