Add Coordinates setter
Sets the corresponding element to the parameter value passed in. Checks against the grid size constraints beforehand and throws RangeError if outside of constraints. Preferred method to set element via coordinates.
This commit is contained in:
parent
5725757aa0
commit
fb481669ed
2 changed files with 34 additions and 4 deletions
|
@ -33,14 +33,18 @@ class Grid<E> extends DelegatingList<E> {
|
|||
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.
|
||||
|
|
|
@ -138,4 +138,30 @@ void main() {
|
|||
expect(sut.toCoordinates(6), equals(Point(0, 2)));
|
||||
}, tags: const ["happy"]);
|
||||
});
|
||||
group("coordinates setter", () {
|
||||
Grid<String> 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"]);
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue