closestTo method

E closestTo(
  1. E target, [
  2. num difference(
    1. E a,
    2. E b
    )?
])

The closest element E to target.

Example:

const [2, 5, 6, 8, 10].closestTo(7) == 6

[Note.c, Note.e, Note.f.sharp, Note.a]
    .closestTo(Note.g, (a, b) => b.semitones - a.semitones)
  == Note.f.sharp

Implementation

E closestTo(E target, [num Function(E a, E b)? difference]) =>
    reduce((closest, element) {
      if (difference == null && closest is! num) {
        throw ArgumentError.value(
          difference,
          'difference',
          'Provide difference when elements are not num',
        );
      }

      difference ??= (a, b) => (b as num) - (a as num);

      return difference!(element, target).abs() <
              difference!(closest, target).abs()
          ? element
          : closest;
    });