NumminorihSF/proposal-array-select-reject

A Stage 0 proposal to add `Array.prototype.select` and `Array.prototype.reject`

★ 0Forks 0GitHub ↗Compare

README

proposal-array-select-reject

A Stage 0 proposal to add Array.prototype.select and Array.prototype.reject.

const array = [1, 2, 3, 4, 5];

// Select is just an alias for Array.p.filter
array.select(i => (i < 3)); // => [1, 2];

// Reject does the opposite of select.
array.reject(i => (i < 3)); // => [3, 4, 5];

Motivation

Array.prototype.filter is confusing. I constantly have to ask myself "am I filtering in, or filtering out the current item?".

"Filtering in"

Implies that returning true would keep the current item.

"Filtering out"

Implies that returning true would remove the current item.

Array.p.filter acts as "filtering in". But when I think of the word "filter", I think of "filtering out". So every time that I attempt to write an array filter, I end up writing the opposite of what I intended.

Array.p.select fixes this confusion. You are selecting the current item. Similarly, Array.p.reject means you are rejecting the current item.

Semantics

Array.prototype.select(callbackfn[, thisArg ])

The initial value of the select property is the same function object as the initial value of the Array.prototype.filter property.

Array.prototype.reject(callbackfn[, thisArg ])

When the reject method is called with one or two arguments, the following steps are taken:

  1. Let O be ? ToObject(this value).
  2. Let len be ? LengthOfArrayLike(O).
  3. If IsCallable(callbackfn) is false, throw a TypeError exception.
  4. If thisArg is present, let T be thisArg; else let T be undefined.
  5. Let A be ? ArraySpeciesCreate(O, 0).
  6. Let k be 0.
  7. Let to be 0.
  8. Repeat, while k < len
    1. Let Pk be ! ToString(k).
    2. Let kPresent be ? HasProperty(O, Pk).
    3. If kPresent is true, then
      1. Let kValue be ? Get(O, Pk).
      2. Let rejected be ! ToBoolean(? Call(callbackfn, T, « kValue, k, O »)).
      3. If rejected is false, then
        1. Perform ? CreateDataPropertyOrThrow(A, ! ToString(to), kValue).
        2. Set to to to + 1.
    4. Set k to k + 1.
  9. Return A.

Related

Contributors

jridgewell

Issues