Array.prototype.contains

Andrea Giammarchi andrea.giammarchi at gmail.com
Wed Jul 23 17:54:23 PDT 2014


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.

Just my 2 cents on an issue I see coming soon on your screens

Regards




On Wed, Jul 23, 2014 at 2:05 PM, Alex Vincent <ajvincent at gmail.com> wrote:

> On Wed, Jul 23, 2014 at 2:00 PM, Michael Haufe <tno at thenewobjective.com>
> wrote:
>
>> Array.prototype.removeAt(index);
>> Array.prototype.remove(element);
>>
>
> We already have an equivalent of removeAt:  Array.prototype.splice(index,
> 1).  My concern about remove still stands.
>
> --
> "The first step in confirming there is a bug in someone else's work is
> confirming there are no bugs in your own."
> -- Alexander J. Vincent, June 30, 2001
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140723/f7456e2c/attachment.html>


More information about the es-discuss mailing list