getEntryIndex1 method

  1. @override
int getEntryIndex1(
  1. double? xValue,
  2. double? closestToY,
  3. Rounding rounding
)
override

Implementation

@override
int getEntryIndex1(double? xValue, double? closestToY, Rounding rounding) {
  if (_values == null || _values!.isEmpty) return -1;

  int low = 0;
  int high = _values!.length - 1;
  int closest = high;

  while (low < high) {
    int m = (low + high) ~/ 2;

    final double d1 = _values![m].x - xValue!,
        d2 = _values![m + 1].x - xValue,
        ad1 = d1.abs(),
        ad2 = d2.abs();

    if (ad2 < ad1) {
      // [m + 1] is closer to xValue
      // Search in an higher place
      low = m + 1;
    } else if (ad1 < ad2) {
      // [m] is closer to xValue
      // Search in a lower place
      high = m;
    } else {
      // We have multiple sequential x-value with same distance

      if (d1 >= 0.0) {
        // Search in a lower place
        high = m;
      } else if (d1 < 0.0) {
        // Search in an higher place
        low = m + 1;
      }
    }

    closest = high;
  }

  if (closest != -1) {
    double? closestXValue = _values![closest].x;
    if (rounding == Rounding.up) {
      // If rounding up, and found x-value is lower than specified x, and we can go upper...
      if (closestXValue < xValue! && closest < _values!.length - 1) {
        ++closest;
      }
    } else if (rounding == Rounding.down) {
      // If rounding down, and found x-value is upper than specified x, and we can go lower...
      if (closestXValue > xValue! && closest > 0) {
        --closest;
      }
    }

    // Search by closest to y-value
    if (!(closestToY!.isNaN)) {
      while (closest > 0 && _values![closest - 1].x == closestXValue) {
        closest -= 1;
      }

      double? closestYValue = _values![closest].y;
      int closestYIndex = closest;

      while (true) {
        closest += 1;
        if (closest >= _values!.length) break;

        final Entry value = _values![closest];

        if (value.x != closestXValue) break;

        if ((value.y - closestToY).abs() <
            (closestYValue! - closestToY).abs()) {
          closestYValue = closestToY;
          closestYIndex = closest;
        }
      }

      closest = closestYIndex;
    }
  }

  return closest;
}