MCPcopy Create free account
hub / github.com/Effect-TS/effect / flattenIterable

Function flattenIterable

packages/effect/src/Stream.ts:2986–3024  ·  view source on GitHub ↗
(self: Stream<Iterable<A>, E, R>)

Source from the content-addressed store, hash-verified

2984 * @since 4.0.0
2985 */
2986export const flattenIterable = <A, E, R>(self: Stream<Iterable<A>, E, R>): Stream<A, E, R> =>
2987 transformPull(self, (pull, scope) => {
2988 let chunk: Arr.NonEmptyReadonlyArray<Iterable<A>> | undefined
2989 let index = 0
2990 let iterator: Iterator<A> | undefined
2991 const refill = Effect.flatMap(pull, (chunk_) => {
2992 chunk = chunk_
2993 index = 0
2994 return loop()
2995 })
2996 function loop(): Pull.Pull<Arr.NonEmptyReadonlyArray<A>, E> {
2997 while (true) {
2998 if (iterator !== undefined) {
2999 const buffer: Array<A> = []
3000 while (buffer.length < DefaultChunkSize) {
3001 const result = iterator.next()
3002 if (result.done) {
3003 iterator = undefined
3004 break
3005 }
3006 buffer.push(result.value)
3007 }
3008 if (Arr.isArrayNonEmpty(buffer)) return Effect.succeed(buffer)
3009 }
3010 if (chunk === undefined) return refill
3011 const iterable = chunk[index++]
3012 if (index === chunk.length) chunk = undefined
3013 if (Array.isArray(iterable)) {
3014 if (Arr.isArrayNonEmpty(iterable)) return Effect.succeed(iterable)
3015 } else {
3016 iterator = iterable[Symbol.iterator]()
3017 }
3018 }
3019 }
3020 return Effect.as(
3021 Scope.addFinalizer(scope, Effect.sync(() => iterator?.return?.())),
3022 Effect.suspend(loop)
3023 )
3024 })
3025
3026/**
3027 * Unwraps `Take` values, emitting elements from non-empty arrays and ending or

Callers

nothing calls this directly

Calls 4

addFinalizerMethod · 0.80
transformPullFunction · 0.70
loopFunction · 0.70
syncMethod · 0.45

Tested by

no test coverage detected