Array.prototype.contains

Mark S. Miller erights at google.com
Thu Feb 23 18:49:33 PST 2012


My point is that if we bother to add any contains method, that it shouldn't
be broken the same way that indexOf is, making it an improvement over
indexOf both in looks *and* in functionality. In other words, do you want

     [3.0, NaN, 4.0].contains(NaN)

to return false? I don't. I wish

    [3.0, NaN, 4.0].indexOf(NaN)

didn't return -1, but it is now too late to fix that.

<only a bit tongue in cheek>
Think this kind of stupidity isn't dangerous? Here's a riddle: Say a
JavaScript implementation, when asked to run the following program, instead
kills the user. Does it conform to the spec?

    [3.0, NaN, 4.0].sort(function compare(a, b) { return a < b ? -1 : a ===
b ? 0 : 1; })

When sorting a valid packed array of valid IEEE floating point values, you
take your life in your hands.
</only a bit tongue in cheek>



On Thu, Feb 23, 2012 at 6:18 PM, Peter Michaux <petermichaux at gmail.com>wrote:

> On Thu, Feb 23, 2012 at 12:35 PM, Mark S. Miller <erights at google.com>
> wrote:
>
> >     if (arr.contains(foo)) {
> >
> > vs
> >
> >     if (arr.indexOf(foo) !== -1) {
>
> The readability of the above two options is very different. The first
> option is far superior as it expresses what the programmer wants to
> know. The second options is an expression of how it can be
> accomplished and requires understanding of indexOf's return values.
>
> I think the addition Array.prototype.contains would be a good, simple
> one that would improve programs. The fact that this function exists in
> libraries means it is useful in a general in the opinion of at least
> several programmers.
>
> Peter
>



-- 
    Cheers,
    --MarkM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120223/30b446cf/attachment.html>


More information about the es-discuss mailing list