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"]); }); }