Function partition

  • Category

    Split an iterable into 2 arrays of elements that passed or failed a provided type guard.

    Time complexity: O(n)

    Space complexity: O(n)

    Type Parameters

    • S
    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to partition

    • typeGuard: ((element) => element is S)

      The type guard to apply to each element of iterable. If the type guard returns a truthy value the element will be added to the passed array in the result. Otherwise, it will be added to the failed array.

        • (element): element is S
        • Parameters

          • element: T

          Returns element is S

    Returns [passed: S[], failed: Exclude<T, S>[]]

    A tuple where the 1st element is an array of elements that passed the predicate (passed) and the 2nd element are the elements that failed the predicate (failed)

    Iterable

    Example

    const [numbers, strings] = partition(['a', 1, 'b', 2, 'c', 3], (element): element is number => typeof element === 'number');

    console.log(numbers); // [1, 2, 3]
    console.log(strings); // ['a', 'b', 'c']
  • Category

    Split an iterable into 2 arrays of elements that passed or failed a provided predicate.

    Time complexity: O(n)

    Space complexity: O(n)

    Type Parameters

    • T

    Parameters

    • iterable: Iterable<T>

      The iterable to partition

    • predicate: ((value, increment) => unknown)

      The predicate to apply to each element of iterable. If the predicate returns a truthy value the element will be added to the passed array in the result. Otherwise, it will be added to the failed array.

        • (value, increment): unknown
        • Parameters

          • value: T
          • increment: number

          Returns unknown

    Returns [passed: T[], failed: T[]]

    A tuple where the 1st element is an array of elements that passed the predicate (passed) and the 2nd element are the elements that failed the predicate (failed)

    Iterable

    Example

    const [odd, even] = partition([1, 2, 3, 4, 5, 6], num => num % 2);

    console.log(odd); // [1, 3, 5]
    console.log(even); // [2, 4, 6]