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];
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.
The initial value of the select
property is the same function object
as the initial value of the Array.prototype.filter
property.
When the reject
method is called with one or two arguments, the
following steps are taken:
- Let
O
be? ToObject(this value)
. - Let
len
be? LengthOfArrayLike(O)
. - If
IsCallable(callbackfn)
isfalse
, throw aTypeError
exception. - If
thisArg
is present, letT
bethisArg
; else letT
beundefined
. - Let
A
be? ArraySpeciesCreate(O, 0)
. - Let
k
be 0. - Let
to
be 0. - Repeat, while
k
<len
- Let
Pk
be! ToString(k)
. - Let
kPresent
be? HasProperty(O, Pk)
. - If
kPresent
istrue
, then- Let
kValue
be? Get(O, Pk)
. - Let
rejected
be! ToBoolean(? Call(callbackfn, T, « kValue, k, O »))
. - If
rejected
isfalse
, then- Perform
? CreateDataPropertyOrThrow(A, ! ToString(to), kValue)
. - Set
to
toto + 1
.
- Perform
- Let
- Set
k
tok + 1
.
- Let
- Return
A
.
- Ruby
- Underscore
- Lodash