@metreeca/pipe - v0.9.11
    Preparing search index...

    Function flatMap

    • Creates a task that transforms each item into a data source and flattens the results.

      Items are processed sequentially by default, preserving output order. In parallel mode, items are processed concurrently and flattened results are emitted as they complete without preserving order.

      Data sources returned by the mapper are handled as follows:

      • undefined - filtered out and not included in the output stream
      • Primitives (strings, numbers, booleans, null): Yielded as single atomic items
      • Arrays/Iterables (excluding strings): Items are yielded individually from each mapper result
      • Async Iterables/Pipes: Items are yielded as they become available
      • Promises: Awaited and then processed according to their resolved value
      • Other values (objects, etc.): Yielded as single items

      The mapper function can be synchronous or asynchronous (returning a Promise). Async mappers are useful for fetching data from APIs, databases, or any async source.

      Type Parameters

      • V

        The type of input items

      • R

        The type of output items after flattening

      Parameters

      • mapper: (item: V) => Data<R> | Promise<(Data<R> | undefined)> | undefined

        The function to transform each item into a data source. When the mapper returns undefined, that value is filtered out and not included in the output stream.

      • parallel: { parallel?: number | boolean } = {}

        Concurrency control: false/undefined/1 for sequential (default), true for parallel with auto-detected concurrency (CPU cores), 0 for unbounded concurrency (I/O-heavy tasks), or a number > 1 for explicit concurrency limit

      Returns Task<V, R>

      A task that transforms and flattens items

      In parallel mode, when an error occurs all pending operations are awaited (but not failed) before the error is thrown to prevent resource leaks.

      // Synchronous mapper
      await items([1, 2, 3])(flatMap(x => [x, x * 2]))(toArray());
      // [1, 2, 2, 4, 3, 6]

      // Async mapper for API calls
      await items([1, 2, 3])(flatMap(async id => {
      const response = await fetch(`/api/items/${id}`);
      return response.json();
      }))(toArray());

      // Parallel processing
      await items([1, 2, 3])(flatMap(async id => {
      const data = await fetchData(id);
      return data.items;
      }, { parallel: true }))(toArray());