-
Notifications
You must be signed in to change notification settings - Fork 34
Description
Currently if I have a List<Foo> sorted on String name field of Foo, I can't binary search for or find lower bound of a String value, because existing functions require the key to be the same type with the list element type.
For example:
core/pkgs/collection/lib/src/algorithms.dart
Lines 39 to 46 in dc97530
| int binarySearchBy<E, K>( | |
| List<E> sortedList, | |
| K Function(E element) keyOf, | |
| int Function(K, K) compare, | |
| E value, [ | |
| int start = 0, | |
| int? end, | |
| ]) { |
A more general version of this function would be:
int binarySearchBy<E, K>(
List<E> sortedList,
K Function(E element) keyOf,
int Function(K, K) compare,
K key, [ // <------- type of value is K instead of E
int start = 0,
int? end,
]) { ... }And then the body of the function would be identical to the current version, except we wouldn't need var key = keyOf(value) line.
A real-world use case for this is in dart_ci's test results backend, which slices a List<Result> sorted by a String name field, using a string value provided by the user.
Since we can't search for a String in a List<Result> using package:collection today, the code currently creates Results with just the name field: https://github.com/dart-lang/dart_ci/blob/f3f8e9a1e488c20f559234bff37815fecb94a623/current_results/lib/src/result.dart#L43-L44
In https://dart-review.googlesource.com/c/dart_ci/+/432080 I'm fixing this by implementing my own lower bound function. Ideally though it would be great if I could just use package:collection.