Preview:
import { Predicate } from '@nolawnchairs/utils'

export namespace Arrays {

  /**
   * Partitions an array into multiple arrays. A single provided predicate
   * will yield two partitions, where the first (0th) array contains items where
   * the predicate returned true, the second with the items where the predicate
   * returned false. If multiple predicates are provided, each nth partition
   * returned will contain a partition of the array whereby the nth
   * predicate returned true
   *
   * @export
   * @template T
   * @param {T[]} array
   * @param {Predicate<T>[]} predicates
   * @return {*}  {T[][]}
   */
  export function partition<T>(array: T[], ...predicates: Predicate<T>[]): T[][] {
    if (predicates.length === 1)
      return array.reduce((acc, item) => predicates[0](item)
        ? (acc[0].push(item), acc)
        : (acc[1].push(item), acc), [[], []])
    return predicates.reduce((acc, partitioner) => {
      return [...acc, array.filter(partitioner)]
    }, [])
  }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter