Skip to content

Suggestion to add Array#partition as well #2

Closed
@MaxGraey

Description

@MaxGraey

Examples

Basics:

const a = 1, b = 2, c = 3, d = 4
const [ab, cd] = [a,b,c,d].partition((_, index) => index >= 2)
const [ac, bd] = [a,b,c,d].partition(value => value % 2 === 0)

Immutable (out of place) Quick Sort:

function quickSort([p, ...tail]) {
  if (!tail.length) return [p, ...tail]
  const [l, r] = tail.partition(x => x > p)
  return [...quickSort(l), p, ...quickSort(r)]
}

quickSort([5, 2, 3, -1])

Efficient and correct implementation usually not trivial:

// not trivial
function partition(arr, callback) {
  return arr.reduce((result, value, index, array) => {
    result[callback(value, index, array) ? 1 : 0].push(value);
    return result;
  }, [[], []]);
}

or

// not efficient (twice linear scan)
function partition(arr, callback) {
  return [
    arr.filter((...args) => !callback(...args)),
    arr.filter(callback)
  ];
}

or based this proposal:

function partition(arr, callback) {
  return [
    arr.filterOut(callback),
    arr.filter(callback)
  ];
}

Related

OCaml: List.partition
Haskell: Data.List.partition
Lodash: _.partition
RxJS: RxJS/partition
Kotlin: Array.partition

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions