Hyperlinkv0.8.0-beta.28

Iterable

Iterable.flattenconsteffect/Iterable.ts:1589
<A>(self: Iterable<Iterable<A>>): Iterable<A>

Flattens an Iterable of Iterables into a single Iterable

Example (Flattening nested iterables)

import { Iterable } from "effect"

// Flatten nested arrays
const nested = [[1, 2], [3, 4], [5, 6]]
const flat = Iterable.flatten(nested)
console.log(Array.from(flat)) // [1, 2, 3, 4, 5, 6]

// Flatten different iterable types
const mixed: Array<Iterable<string>> = ["ab", "cd"]
const flatMixed = Iterable.flatten(mixed)
console.log(Array.from(flatMixed)) // ["a", "b", "c", "d"]

// Flatten deeply nested (only one level)
const deepNested = [[[1, 2]], [[3, 4]]]
const oneLevelFlat = Iterable.flatten(deepNested)
console.log(Array.from(oneLevelFlat).map((arr) => Array.from(arr)))
// [[1, 2], [3, 4]] (still contains arrays)

// Empty iterables are handled correctly
const withEmpty = [[1, 2], [], [3, 4], []]
const flatWithEmpty = Iterable.flatten(withEmpty)
console.log(Array.from(flatWithEmpty)) // [1, 2, 3, 4]
sequencing
export const flatten = <A>(self: Iterable<Iterable<A>>): Iterable<A> => ({
  [Symbol.iterator]() {
    const outerIterator = self[Symbol.iterator]()
    let innerIterator: Iterator<A> | undefined
    function next() {
      if (innerIterator === undefined) {
        const next = outerIterator.next()
        if (next.done) {
          return next
        }
        innerIterator = next.value[Symbol.iterator]()
      }
      const result = innerIterator.next()
      if (result.done) {
        innerIterator = undefined
        return next()
      }
      return result
    }
    return { next }
  }
})
Referenced by 2 symbols