Function flat

  • Expands / flattens sub-iterables up to the specified depth (default is 1), with support for skip logic.

    import {pipe, flat} from 'iter-ops';

    const i = pipe(
    ['one', [2, 3, [4, 5]]],
    flat(2)
    );

    console.log(...i); //=> 'o', 'n', 'e', 2, 3, 4, 5

    It implements the logic similar to Array.flat, handling non-iterable values without throwing errors (unlike spread), and with optional depth support. However, unlike Array.flat, this operator expands all iterable values, including strings. If you want to prevent certain values from being expanded, you can pass in second parameter - skip(value, level) callback function:

    const i = pipe(
    ['one', [1, 2, 3]],
    flat(1, v => typeof v === 'string') // skip expanding strings
    );

    console.log(...i); //=> 'one', 1, 2, 3

    Parameter level in the skip callback represents current depth level = 0, ...depth - 1

    Note that when handling a synchronous iterable, this operator can only expand synchronous sub-iterables. But when handling an asynchronous iterable, it can expand mixed sub-iterables, i.e. any combination of synchronous and asynchronous sub-iterables.

    Compare it to a more strict spread operator.

    Type Parameters

    • T
    • N extends number = 1

    Parameters

    • Optionaldepth: N
    • Optionalskip: ((value: any, level: number) => boolean)
        • (value, level): boolean
        • Parameters

          • value: any
          • level: number

          Returns boolean

    Returns Operation<T, Flatten<T, N>>