From 3f939601b3ac680e157144ff1d7a8565baff2f2b Mon Sep 17 00:00:00 2001 From: Marty Oehme Date: Thu, 30 Aug 2018 09:41:43 +0200 Subject: [PATCH] Add toIndex method can be used to get the correct index from coordinates passed in. Will only calculate the index, not take into consideration any grid size constraints etc. --- lib/src/Grid.dart | 9 ++++++++- test/src/grid_test.dart | 36 +++++++++++++++++++++--------------- 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/lib/src/Grid.dart b/lib/src/Grid.dart index e6bf335..8fe745c 100644 --- a/lib/src/Grid.dart +++ b/lib/src/Grid.dart @@ -37,7 +37,14 @@ class Grid extends DelegatingList { void set(int x, int y, E value) => setElement(x, y, value); - int toIndex(int x, int y) => y * width + x; + /// 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 + /// constraints etc; use [get] for that (generally recommended). + int toIndex(int x, int y) => (x < 0 || y < 0) + ? throw RangeError("Coordinates for Grid Indexing must not be negative.") + : y * width + x; Point toCoords(int index) => Point(index % width, index ~/ width); } diff --git a/test/src/grid_test.dart b/test/src/grid_test.dart index 290b183..70adb30 100644 --- a/test/src/grid_test.dart +++ b/test/src/grid_test.dart @@ -3,7 +3,6 @@ import 'package:test/test.dart'; @Tags(const ["nobrowser"]) void main() { - Grid sut; group("Instantiation", () { List l; setUp(() { @@ -69,23 +68,30 @@ void main() { expect(sut.width, 3); }, tags: const ["happy"]); }); - group("getter", () { + group("toIndex", () { + Grid sut; setUp(() { sut = Grid(3, 3); - sut.setAll(0, [ - "Hey", - "you", - "me", - "together", - "Hello", - "World", - "I", - "am", - "ready." - ]); }); - test("Engine can be instantiated without canvas", () { - expect(sut, isNot(throwsNoSuchMethodError)); + test("throws RangeError on negative x argument", () { + expect(() => sut.toIndex(-1, 2), throwsA(isRangeError)); + }, tags: const ["bad"]); + test("throws RangeError on negative y argument", () { + expect(() => sut.toIndex(2, -1), throwsA(isRangeError)); + }, tags: const ["bad"]); + test("calculates correct index for first element", () { + expect(sut.toIndex(0, 0), equals(0)); + }, tags: const ["happy"]); + test("calculates correct index for last element", () { + expect(sut.toIndex(2, 2), equals(8)); + }, tags: const ["happy"]); + test("calculates correct index for element on first row", () { + expect(sut.toIndex(2, 0), equals(2)); + }, tags: const ["happy"]); + test("calculates correct index for example element", () { + expect(sut.toIndex(1, 1), equals(4)); + }, tags: const ["happy"]); + }); }); }); }