Skip to content

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

Notifications You must be signed in to change notification settings

c3ll256/proposal-array-select-reject

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

056e361 · Oct 24, 2019

History

6 Commits
Oct 24, 2019

Repository files navigation

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

About

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

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published