Array.prototype.contains

Andrea Giammarchi andrea.giammarchi at gmail.com
Thu Jul 24 09:50:48 PDT 2014


What is this about? Not an answer nor a solution to what I've said...
Just think that NaN is rarely an explicit value, rather something
potentially generated at runtime. Would
you .some(Number.isNAN.bind(Number)) all the Arrays? I don't think so,
at least I wouldn't

Sent from my Windows Phone From: Garrett Smith
Sent: ‎7/‎23/‎2014 22:31
To: Andrea Giammarchi
Cc: Alex Vincent; es-discuss at mozilla.org
Subject: Re: Array.prototype.contains
On 7/23/14, Andrea Giammarchi <andrea.giammarchi at gmail.com> wrote:
> agreed, already imagining loops like
>
> ```js
> while (arr.contains(value)) arr.remove(value);
> ```
>
> although that looks a bit nicer than
>
> ```js
> var i;
> while (-1 < (i = arr.indexOf(value))) arr.splice(i, 1);
> ```
>
> my main concern about `.contains()` is its potentially un-optimal
> implementation and error prone logic.
>
> Most of the time we want to know if an array contains something to avoid
> duplicated because we are missing `.unique()`
>
> ```js
> if (!arr.contains(obj)) arr.push(obj);
> ```
>
> Most other times we want to do some action with that contained value or its
> index and here we have a redundant and error prone cases:
>
> ```js
> if (arr.contains(obj)) {
>   // need the index anyway
>   var i = arr.indexOf(obj); // but this might fail !!!!
>   // splice or do other things ...
> }
> ```
>
> AFAIR the latter `.contains()` does not suffer same problems `.indexOf()`
> does and this will result in incompatible operations with array indexes,
> assuming contains told us we are good to go.
>
> As example, `.contains(NaN)` can cause disaster-prone logics if followed by
> `.indexOf(NaN)` because the first check will tell the developer at runtime
> for sure something was there while the second check will return a lovely -1
> most likely unexpected inside the block that believe `.contains(value)` was
> a safe bet.
>


// Contains NaN:
[1, NaN, ].some(function(e) {return Number.isNaN(e);})
-- 
Garrett
@xkit
ChordCycles.com
garretts.github.io


More information about the es-discuss mailing list