import 'dart:math' as math; /// A robust, immutable 2D coordinate. class Coordinate2D implements Comparable { final double x; final double y; const Coordinate2D(this.x, this.y); /// Factory for a (0,0) coordinate. static const Coordinate2D zero = Coordinate2D(0.0, 0.0); // --- Core Logic --- /// Returns the Euclidean distance between this and [other]. /// Uses the formula: $$d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$$ double distanceTo(Coordinate2D other) { final dx = x - other.x; final dy = y - other.y; return math.sqrt(dx * dx + dy * dy); } /// True if both ordinates are finite (not NaN or Infinity). bool get isValid => x.isFinite && y.isFinite; Coordinate2D operator +(Coordinate2D other) => Coordinate2D(x + other.x, y + other.y); Coordinate2D operator -(Coordinate2D other) => Coordinate2D(x - other.x, y - other.y); Coordinate2D operator *(double factor) => Coordinate2D(x * factor, y * factor); Coordinate2D operator /(double divisor) => Coordinate2D(x / divisor, y / divisor); @override bool operator ==(Object other) => identical(this, other) || other is Coordinate2D && runtimeType == other.runtimeType && x == other.x && y == other.y; @override int get hashCode => Object.hash(x, y); @override int compareTo(Coordinate2D other) { if (x != other.x) return x.compareTo(other.x); return y.compareTo(other.y); } @override String toString() => 'Coordinate($x, $y)'; }