From 6c3fcbe7b0a5b1f5c9eaecedb342a8656cbfeaee Mon Sep 17 00:00:00 2001 From: Marty Oehme Date: Thu, 30 Aug 2018 09:43:46 +0200 Subject: [PATCH] Add .get method for coordinate element retrieval to grid Coordinates passed in access the correct index in the internal list. --- lib/src/Grid.dart | 8 +++----- test/src/grid_test.dart | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/lib/src/Grid.dart b/lib/src/Grid.dart index 8fe745c..bbe10eb 100644 --- a/lib/src/Grid.dart +++ b/lib/src/Grid.dart @@ -21,10 +21,10 @@ class Grid extends DelegatingList { height = h, super(l); - E elementAtPos(int x, int y) { + E get(int x, int y) { int i = toIndex(x, y); - if (i >= length) throw RangeError.index(i, this); - _internal[i]; + if (i >= length || x > width - 1) throw RangeError.index(i, this); + return _internal[i]; } void setElement(int x, int y, E value) { @@ -33,8 +33,6 @@ class Grid extends DelegatingList { _internal[i] = value; } - E get(int x, int y) => elementAtPos(x, y); - void set(int x, int y, E value) => setElement(x, y, value); /// Calculate list index from coordinates. diff --git a/test/src/grid_test.dart b/test/src/grid_test.dart index 70adb30..6190c7d 100644 --- a/test/src/grid_test.dart +++ b/test/src/grid_test.dart @@ -92,6 +92,27 @@ void main() { expect(sut.toIndex(1, 1), equals(4)); }, tags: const ["happy"]); }); + group("coordinates getter", () { + Grid sut; + setUp(() { + sut = Grid(3, 3); + sut.setAll(0, + ["Hey", "you", "me", "together", "Hello", null, "I", "am", "ready."]); }); + test("returns null if no element exists at the position requested", () { + expect(sut.get(2, 1), null); + }, tags: const ["sad"]); + test("throws RangeError if requesting element outside of grid width", () { + expect(() => sut.get(4, 1), throwsRangeError); + }, tags: const ["bad"]); + test("throws RangeError if requesting element outside of grid height", () { + expect(() => sut.get(1, 4), throwsRangeError); + }, tags: const ["bad"]); + test("returns element at correct index", () { + expect(sut.get(1, 0), "you"); + }, tags: const ["happy"]); + test("returns last element correctly", () { + expect(sut.get(2, 2), "ready."); + }, tags: const ["happy"]); }); }