Skip to content

Binary search and lower bound functions can be generalized #895

Open
@osa1

Description

@osa1

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:

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions