google / quiver-dart

A set of utility libraries for Dart
https://pub.dev/packages/quiver
Apache License 2.0
1.02k stars 133 forks source link

Provide collections that take custom comparators #104

Open yjbanov opened 10 years ago

yjbanov commented 10 years ago

A common use-case in applications is to use objects as keys whose equals/hashCode is different from the use-case at hand. The most common example that I keep hearing is you want to use database entities as map keys and set elements but you want to have ID-based identity, so for example {id: 1, name: "foo"} and {id: 1, name: "bar"} are considered equal.

Feature request: provide implementations of Map, Set and List that take a comparator function as a constructor parameter and use it to compare keys and elements.

seaneagan commented 10 years ago

Looks like there is already some work on this in the collection package:

https://api.dartlang.org/apidocs/channels/stable/#collection/dart-pkg-collection-equality

So Equalitys would take the place of Comparators. The only thing left would be to Provide the actual collections which take Equalitys in their constructors. Maybe there are already plans to add those to the collection package ?

seaneagan commented 10 years ago

Looks like the HashMap and HashSet constructors already support this:

https://api.dartlang.org/apidocs/channels/stable/#dart-collection.HashMap@id_HashMap- https://api.dartlang.org/apidocs/channels/stable/#dart-collection.HashSet@id_HashSet-

They take custom equals and hashCode Functions, so something like:

new HashSet<DBEntity>(equals: (e1, e2) => e1.id == e2.id, hashCode: (e) => e.id.hashCode);