Skip to main content

type partition

Returns a Reducer that splits the incoming values into two separate outputs based on the given pred predicate. Values for which the predicate is true are fed into the collectorTrue reducer, and other values are fed into the collectorFalse instance. If no collectors are provided the values are collected into arrays.

note

if the predicate is a type guard, the return type is automatically inferred

example
Stream.of(1, 2, 3).partition((v) => v % 2 === 0)
// => [[2], [1, 3]]
Stream.of<number | string>(1, 'a', 'b', 2)
.partition((v): v is string => typeof v === 'string')
// => [['a', 'b'], [1, 2]]
// return type is: [string[], number[]]
Stream.of(1, 2, 3, 4).partition(
(v) => v % 2 === 0,
{ collectorTrue: Reducer.toJSSet(), collectorFalse: Reducer.sum }
)
// => [Set(2, 4), 4]

Definition

partition: {
    <T, T2 extends T, RT, RF = RT>(pred: (value: T, index: number) => value is T2, options: {
      collectorTrue: Reducer<T2, RT>;
      collectorFalse: Reducer<Exclude<T, T2>, RF>;
    }): Reducer<T, [true: RT, false: RF]>;
    <T, T2 extends T>(pred: (value: T, index: number) => value is T2, options?: {
      collectorTrue?: undefined;
      collectorFalse?: undefined;
    }): Reducer<T, [true: T2[], false: Exclude<T, T2>[]]>;
    <T, RT, RF = RT>(pred: (value: T, index: number) => boolean, options: {
      collectorTrue: Reducer<T, RT>;
      collectorFalse: Reducer<T, RF>;
    }): Reducer<T, [true: RT, false: RF]>;
    <T>(pred: (value: T, index: number) => boolean, options?: {
      collectorTrue?: undefined;
      collectorFalse?: undefined;
    }): Reducer<T, [true: T[], false: T[]]>;
  }