diff --git a/lib/src/Grid.dart b/lib/src/Grid.dart index b009a99..40b87ea 100644 --- a/lib/src/Grid.dart +++ b/lib/src/Grid.dart @@ -33,14 +33,18 @@ class Grid extends DelegatingList { return _internal[i]; } - void setElement(int x, int y, E value) { + /// Sets element at coordinate position + /// + /// Sets the corresponding element to the [E] parameter [value] passed in. + /// Checks against the grid size constraints beforehand and throws + /// [RangeError] if outside of constraints. Preferred method to set + /// elements via coordinates. + void set(int x, int y, E value) { int i = toIndex(x, y); - if (i >= length) throw RangeError.index(i, this); + if (i >= length || x > width - 1) throw RangeError.index(i, this); _internal[i] = value; } - void set(int x, int y, E value) => setElement(x, y, value); - /// Calculate list index from coordinates /// /// Can be used to get the correct index from coordinates passed in. diff --git a/test/src/grid_test.dart b/test/src/grid_test.dart index 1486ee9..07dd467 100644 --- a/test/src/grid_test.dart +++ b/test/src/grid_test.dart @@ -138,4 +138,30 @@ void main() { expect(sut.toCoordinates(6), equals(Point(0, 2))); }, tags: const ["happy"]); }); + group("coordinates setter", () { + Grid sut; + setUp(() { + sut = Grid(3, 3); + sut.setAll(0, + ["Hey", "you", "me", "together", "Hello", null, "I", "am", "ready."]); + }); + test("sets element to null if passing null in", () { + sut.set(1, 1, null); + expect(sut.get(1, 1), null); + }, tags: const ["sad"]); + test("throws RangeError if setting element outside of grid width", () { + expect(() => sut.set(4, 1, "testValue"), throwsRangeError); + }, tags: const ["bad"]); + test("throws RangeError if setting element outside of grid height", () { + expect(() => sut.set(1, 4, "testValue"), throwsRangeError); + }, tags: const ["bad"]); + test("sets element at correct index", () { + sut.set(1, 0, "testValue"); + expect(sut.get(1, 0), "testValue"); + }, tags: const ["happy"]); + test("sets last element correctly", () { + sut.set(2, 2, "testValue"); + expect(sut.get(2, 2), "testValue"); + }, tags: const ["happy"]); + }); }