Skip to content

Add Collection.contains method #1030

Closed
Closed
@DartBot

Description

@DartBot

This issue was originally filed by @seaneagan


There are currently several methods to determine if a collection
"contains" a value:

map.containsKey(key)
map.containsValue(value)
set.contains(item)
list.indexOf(item) != -1

I propose unifying these into a Collection.contains method, whose
default implementation would be something like:

contains (T item) {
 for(final T i in this) {
   if(item == i) {
     return true;
   }
 }
 return false;
}

I use item == i rather than i == item since the caller likely
knows and cares more about the == method of the item they pass in than
that of each item in the collection. Another option would be item === i, but I think that is a less common use case which could be done
via a separate "containsIdentical" method.

It also might make sense to shorten Map's getKeys()/getValues() to
just keys/values (getters). I assume, as in Java, that these methods
return Collections which are backed by the original Map, and thus are
O(1). Then the above examples would simplify to:

map.keys.contains(key);
map.values.contains(value);
set.contains(item);
list.contains(item);

... and even if you don't know the particular Collection sub-interface
of a collection, you can still easily test whether it contains an
item:

collection.contains(item);

List.indexOf would still be necessary for determining the exact index
at which the list contains the item, but Map.containsKey,
Map.containsValue, and Set.contains could all be removed.

FWIW, JavaScript doesn't yet have a builtin collections framework, but
the need for a "contains" method for lists is being discussed for ES6
(see https://mail.mozilla.org/pipermail/es-discuss/2011-December/019099.html),
and the most popular collections library
(http://documentcloud.github.com/underscore/) has a "contains" method
similar to what I am proposing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-core-librarySDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries.closed-obsoleteClosed as the reported issue is no longer relevant

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions