Skip to content

Instantly share code, notes, and snippets.

@sebakerckhof
Last active November 15, 2019 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebakerckhof/0dc71038af712753a0437311ee2862b6 to your computer and use it in GitHub Desktop.
Save sebakerckhof/0dc71038af712753a0437311ee2862b6 to your computer and use it in GitHub Desktop.
Array.prototype.partition proposal

Array.prototype.partition proposal

Motivation

Currently there is no way to partition an array into multiple parts based on a callback function, without calling filter multiple times.

const callback = (item) => someCondition;
const matchingItems = arrayToPartition(callback);
const nonMatchingItems = arrayToPartition(item => !callback(item));

This approach has the downside of iterating over the array multiple times.

An alternate solution is to manually iterate over the array:

const callback = (item) => someCondition;
const matchingItems = [];
const nonMatchingItems = [];
for (const item of arrayToPartition) {
  if (callback(item)) {
    matchingItems.push(item);
  } else {
    nonMatchingItems.push(item);
  }
}

This approach is efficient, but requires a lot of code.

Proposed solution

We propose the addition of a new method to the Array prototype - partition. This would give developers a straight-forward way to accomplish this common, basic operation.

const callback = (item) => someCondition;
const [nonMatchingItems, matchingItems] = arrayToPartition.partition(callback);

This could potentially be extended so that callback can also return any integer >= 0, which would then partition that item into an array matching that index in the return value. In this case you could still return a boolean value where false = 0, true = 1 and thus the return value is consistent.

High-level API

The proposed signature is the same as the existing Array.prototype.filter method:

Array.prototype.partition(callback[, thisArg])

Comparison to other languages

FAQ

What are the main benefits?

A simplified API

Specification

TODO

Implementations

  • Polyfills: TODO (but trivial)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment