From 5a72783d57cc9837852ba6f4347f0464924cc2bd Mon Sep 17 00:00:00 2001 From: Marty Oehme Date: Thu, 30 Aug 2018 09:52:00 +0200 Subject: [PATCH] Add .toCoordinates() method to grid Calculates the 2-D array coordinates from the corresponding list index passed in. Relies on grid width to calculate coordinates. Does not check against grid size constraints. --- lib/src/Grid.dart | 11 +++++++++-- test/src/grid_test.dart | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/src/Grid.dart b/lib/src/Grid.dart index bbe10eb..04d8d3c 100644 --- a/lib/src/Grid.dart +++ b/lib/src/Grid.dart @@ -35,7 +35,7 @@ class Grid extends DelegatingList { void set(int x, int y, E value) => setElement(x, y, value); - /// Calculate list index from coordinates. + /// Calculate list index from coordinates /// /// Can be used to get the correct index from coordinates passed in. /// Will only calculate the index, not take into consideration any grid size @@ -44,5 +44,12 @@ class Grid extends DelegatingList { ? throw RangeError("Coordinates for Grid Indexing must not be negative.") : y * width + x; - Point toCoords(int index) => Point(index % width, index ~/ width); + /// Calculate coordinates from list index + /// + /// Calculates the 2-D array coordinates from the corresponding list index + /// passed in. Relies on grid width to calculate coordinates. Does not check + /// against grid size constraints; use [set] for that (generally recommended). + Point toCoordinates(int index) => (index < 0) + ? throw RangeError("Index for Grid Coordinates must not be negative") + : Point(index % width, index ~/ width); } diff --git a/test/src/grid_test.dart b/test/src/grid_test.dart index 6190c7d..1486ee9 100644 --- a/test/src/grid_test.dart +++ b/test/src/grid_test.dart @@ -1,3 +1,5 @@ +import 'dart:math'; + import 'package:rules_of_living/src/Grid.dart'; import 'package:test/test.dart'; @@ -115,4 +117,25 @@ void main() { expect(sut.get(2, 2), "ready."); }, tags: const ["happy"]); }); + group("toCoords", () { + Grid sut; + setUp(() { + sut = Grid(3, 3); + }); + test("throws RangeError on negative index argument", () { + expect(() => sut.toCoordinates(-1), throwsA(isRangeError)); + }, tags: const ["bad"]); + test("calculates correct index for first element", () { + expect(sut.toCoordinates(0), equals(Point(0, 0))); + }, tags: const ["happy"]); + test("calculates correct index for last element", () { + expect(sut.toCoordinates(8), equals(Point(2, 2))); + }, tags: const ["happy"]); + test("calculates correct index for last element on first row", () { + expect(sut.toCoordinates(2), equals(Point(2, 0))); + }, tags: const ["happy"]); + test("calculates correct index for example element", () { + expect(sut.toCoordinates(6), equals(Point(0, 2))); + }, tags: const ["happy"]); + }); }